Javascript – Does javascript support numerically indexed arrays with a more optimized algorithm than an associative array

javascriptperformance

I know that Python, Perl, Java, Lua and obviously C (as it's the only array that's in ANSI standard afaik) support faster looking of numerically indexed arrays than doing a hash lookup or anything like that. Does Javascript also?

As an example in code of what I mean, in the case of Perl:

for(i=0;i<10;i++)
{
  # Do something
}

is slower than:

for (1..9)
{
  # do something else
}

or:

@var = (1,2,3)
foreach(@var)
{
  print $_; # look I'm fancy
}

and faster than:

foreach my $key (keys %hash) 
{
  print $_; # Look I'm fancy
}

and in python, given the following:

class thisClass:
  def methodOne(i):
    return i+1

thisDict = { 
  'number': 1
}

These two operations are similar in speed because both involve a hash lookup into a same-widthed hash:

thisObject = new thisClass
i  = thisObject.methodOne(1)

and:

i = 1+thisDict['1'];

Both of these kinds of lookups are slower than this:

thisTuple = (1,)
i = thisTuple[0]+1

While this:

thisArray = [1,2]

for i in thisArray:
 print i

is iterated faster than:

thisTuple = (1,2)

for i in thisTuple:
  print i

by which I mean lists iterate faster than tuples.

Does Javascript support numerically indexed arrays differently than associatinve arrays? I don't believe Javascript supports more than arrays and associative arrays, but if it does how do they compare to the two speed wise?

Best Answer

JavaScript does not have any explicit way to specify that you want a normal array rather than an object--everything is an object by default. However, modern JavaScript engines have aggressive optimizations for objects that act like arrays. (Here is a good overview of what V8 does, for example.)

Modern JavaScript engines use "just-in-time compilation" (JIT). This means they optimize code based on how it's used at runtime. If the engine sees that an object is being accessed with consecutive numeric indices, it can optimize these into an array-like structure. However, this may take some time to take effect, which you should keep in mind if you want to write your own benchmarks.

Unfortunately, these are all optimizations that are not part of the language's semantics. This means that you cannot rely on any of them across engines. So if you're writing code that would benefit from array-like semantics, treat your objects just like normal arrays and be sure to profile on your target interpreter(s).

Additionally, for very specific use-cases, JavaScript has typed arrays. If you have raw binary data--like an array of ints or floats--you can take advantage of these typed arrays for storing, reading and writing them much more efficiently.

Unfortunately, you may have some issues with browser support of typed arrays. They have only been recently added to the proprietary browsers, so if you need to support IE <10 or Safari <5.1, you can't use them.