0

Consider the following code:

var _test1 = [];
_test1[88] = 'sex';
_test1[1999990] = 'hey';
for(i = 0, length = _test1.length; i < length; i++){
    if(_test1[i] == 'hey'){
        alert(_test1.length);
    }
}

this takes a lot of time, and there are only 2 values. Is there any way to be faster? Even by using another system that index objects by a number and then loop them fast?

T J
  • 42,762
  • 13
  • 83
  • 138
Totty.js
  • 15,563
  • 31
  • 103
  • 175

2 Answers2

3

You can use a for / in loop:

for (var i in _test1) {
    if (!_test1.hasOwnProperty(i) || isNaN(+i)) continue;

    if(_test1[i] == 'hey'){
        alert(_test1.length);
    }
}

This is exactly what you're looking for; it will only loop over the indices that are actually defined, and will skip any holes in the array.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

Have you tried using an Object instead? Numbers should be converted to strings automatically. You would traverse the list with a for...in loop.

Juan Pablo Califano
  • 12,213
  • 5
  • 29
  • 42
  • You don't need to switch to an Object. – SLaks Apr 25 '10 at 19:59
  • yes. i think this is the best option. are objects much more heavy than array? – Totty.js Apr 25 '10 at 20:01
  • Right. You don't have to. But if you have a sparse array, you'll end up with a hash table under the hood. So, maybe using one is more suitable (though this might not be the case for the OP's problem, there's little context). – Juan Pablo Califano Apr 25 '10 at 20:05
  • @Juan: There is no difference at all between a sparse array and a normal array. – SLaks Apr 25 '10 at 20:06
  • @Totty As SLaks said, Arrays are Objects, plus other stuff. Depending on what are you storing and how you will access the data, going with an Object might make more sense than an Array, or not. – Juan Pablo Califano Apr 25 '10 at 20:08
  • @SLaks. You could be right, but I'll re check. I know they are different in Actionscript, but that' s implementation dependent anyway. I think it makes sense to switch to hash tables for sparse arrays, though. – Juan Pablo Califano Apr 25 '10 at 20:11
  • @Juan: They're both hashtables. – SLaks Apr 25 '10 at 20:16
  • @SLaks. As I said, that's really implementation dependent. Anyway, some JS implementations such as V8, SpiderMonkey, etc, seem to be using this dual storage technique. http://stackoverflow.com/questions/614126/why-is-array-push-sometimes-faster-than-arrayn-value/614255#614255 – Juan Pablo Califano Apr 25 '10 at 20:22