# [as3]This had me bugging for a long time.

17 posts

 Hello everyone. For months i had one question in mind: what happens when we do this: ```//a is an array //b is true or false, depends on i for (i = 0; i=0;i--){ if(b){ a.splice(i,1); } }``` ```//Option 3 for(var i:int = 0;i=0;i--){ if(b){ a[i] = a[a.length-1]; a.length--; } }```Unless, of course, you can do this… (I don’t know if it’ll work or not, and I can’t test at the moment) ```//Option 5 for(var i:int = a.length-1;i>=0;i--){ if(b){ a[i] = a[a.length--]; } }``` You could always test it in your browser… It shrinks the array length before accessing the element at the end. I went ahead and tested these algorithms. Benchmark: You are given a list that is 120 items long. 100 items are the string “yes” and 20 are the string “no”. (The exact criterion used is: `i % 11 == 0 || i % 13 == 0`.) The goal is to remove all “no” strings. Displayed below is the time it takes to complete 10000 trials. Each trial includes the overhead of creating a new copy of the source list, plus the (much smaller) overhead of ensuring that the list ended up with a length of exactly 100. Option 1: 0.282s Option 2: 0.281s Option 3: 0.0501s Option 4: 0.0501s Option 5: [Skipped because it doesn’t work] Originally posted by UnknownGuardian:Write ALL the options! Ok then: Option 6: 0.0760s Option 7: 0.0768s Code for option 6: ```for(var i:int = 0; i < a.length; i++){ if(b){ a[i] = null; } } var remainingCount:int = 0; for(var i:int = 0; i < a.length; i++) { if(a[i] != null) { a[remainingCount] = a[i]; remainingCount++; } } a.length = remainingCount; ``` And option 7 is the same, except that the first loop iterates backwards. So in conclusion, it doesn’t really matter (at least in Flash) whether you iterate forwards or backwards. You just don’t want to call `splice()` many times. Not sure if I wrote this right (I checked a case or two and it seems right), but could you bench this too? Just combined your 2 loops into 1. ```var current:int = 0; for (var i:int = 0; i < a.length; i++) { if(i != current)// if not same slot { a[current] = a[i]; } if (!b) //keep condition << this is not throw away condition! (should be !b) { current++; } } a.length = current; trace("end", a); ``` Option 8: 0.0480s Nice! A new fastest method for looping. What if we take option 8 and do `++i` instead of `i++` (in both places its used)? IIRC, that’s ~5% faster. (Also, what is b in `if (!b)`? By my understanding that evaluates to `if(true)`…) b is the drop condition. i.e. `(i % 13 == 0 || i % 11 == 0)` !b is the keep condition. Actually, the drop condition is `a[i] == no`, where `no` is a variable with value `"no"`. The array was populated based on that other condition, though. And I was using `++i`. Originally posted by UnknownGuardian:b is the drop condition. i.e. `(i % 13 == 0 || i % 11 == 0)` !b is the keep condition. Ah ha. Stand-in condition. Foo == Bar.