Dino
Dino

Reputation: 149

Javascript: indexOf slow on high index despite sparse array?

While running some tests on my site, I ended up with an array that has only 10 String in it, but one with a very high index (600 000 000).

Running indexOf on this array is very slow, making the whole tab freeze for several seconds for each call.

When I tried looking for information about this, most seemed to be saying that modern Javascript implementations use sparse array and that it shouldn't be a problem. I'm using the latest Chrome 62.

The issue is actually reproducible just in the Developer Tools' console. If you try running the following code :

test = [];
test[600000000] = "test";
test.indexOf("test");

You'll see that the console takes several seconds to return the index, indicating that Javascript is looping through every index from 0 to 600000000 rather than skipping directly to the one element. Is this normal behavior?

Upvotes: 4

Views: 2283

Answers (1)

dave
dave

Reputation: 64657

I'm not sure if this is "normal" behaviour, but an easy replacement would be:

function sparseIndexOf(arr, value) {
    return Object.keys(arr).find(function(k) {
        return arr[k] === value;
    })
}

test = [];
test[600000000] = "test";
sparseIndexOf(test, "test")

Upvotes: 6

Related Questions