views:

38

answers:

2
    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?

Or to use another system that index objects by a number and then loop them fast? thanks

+2  A: 

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
thanks for this solution, i will benchmark later :D
Totty
+1  A: 

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
You don't need to switch to an Object.
SLaks
yes. i think this is the best option. are objects much more heavy than array?
Totty
Arrays are objects.
SLaks
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
@Juan: There is no difference at all between a sparse array and a normal array.
SLaks
@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
@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
@Juan: They're both hashtables.
SLaks
@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