Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Do longer keys make object lookup slower?

The question title almost says it all: do longer keys make for slower lookup? Is:

someObj["abcdefghijklmnopqrstuv"]

Slower than:

someObj["a"]

Another sub-question is whether the type of the characters in the string used as key matters. Are alphanumeric key-strings faster?

I tried to do some research; there doesn't seem to be much info online about this. Any help/insight would be extremely appreciated.

like image 922
Chris Avatar asked Dec 18 '12 19:12

Chris


People also ask

Are object values slow?

Conclusion. It turns out that Object. values is about 3.2 times faster than Object.

Are objects faster than arrays JavaScript?

The short version: Arrays are mostly faster than objects.

Can JavaScript object have same keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.


2 Answers

In general no. In the majority of languages, string literals are 'interned', which hashes them and makes their lookup much faster. In general, there may be some discrepancies between different javascript engines, but overall if they're implemented well (cough IE cough), it should be fairly equal. Especially since javascript engines are constantly being developed, this is (probably) an easy thing to optimize, and the situation will improve over time.

However, some engines also have limits on the length of strings that are interned. YMMV on different browsers. We can also see some insight from the jsperf test (linked in comments for the question). Firefox obviously does much more aggressive interning.

As for the types of characters, the string is treated as just a bunch bytes no matter the charset, so that probably won't matter either. Engines might optimize keys that can be used in dot notation but I don't have any evidence for that.

like image 59
forivall Avatar answered Nov 10 '22 07:11

forivall


The performance is the same if we are talking about Chrome which uses V8 javascript engine. Based on V8 design specifications you can see from "fast property access" and "Dynamic machine code generation" that in the end those keys end up being compiled as any other c++ class variables.

like image 36
csg Avatar answered Nov 10 '22 08:11

csg