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.
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.
Share Improve this question asked Dec 18, 2012 at 19:38 ChrisChris 26.9k6 gold badges60 silver badges72 bronze badges 3- 2 Why not run some tests on jsPerf? – j08691 Commented Dec 18, 2012 at 19:40
- 2 jsperf./array-key-length-performance-impact – Ricardo Lohmann Commented Dec 18, 2012 at 19:41
- 1 @j08691 Well that's a good idea, but I generically am not a fan of taking jsPerf-tests as conclusive evidence. There are many specifics that tend to affect the results. I just want to know how mon implementations (V8, etc.) are theoretically expected to perform. – Chris Commented Dec 18, 2012 at 19:41
2 Answers
Reset to default 6In 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 ments 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.
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 piled as any other c++ class variables.