I'm writing a JS object that needs to perform really basic key-value caching on string:function pairs. The class runs on the client and caches partially-compiled templates for rendering part of the page, so it may have anywhere from 20-200 items.
Before actually writing the class, I figured it would be a good idea to see what the fastest cache retrieval method was. The options that came to mind were:
1. Basic property access:
if (x[k] !== undefined) {
v = x[k];
}
2. Key Check (Own):
if (x.hasOwnProperty(k)) {
v = x[k];
}
3. Key Check (General):
if (k in x) {
v = x[k];
}
I assumed that 3 would be fastest (checks to see if the property exists but doesn't retrieve it or worry about where it exists) and 1 would be slowest (actually gets the property, even if it doesn't do anything).
Putting all of these into jsPerf yielded some very strange results. In both Chrome (and Chromium) and IE, #1 is about twice as fast. In Firefox, #3 has a minor edge, but performance is similar between all three. It didn't matter if I was running in a VM or not, and didn't change a lot between versions.
I'm having trouble explaining these results. It might be that #1 notices that nothing will happen to the data and so just checks for the key internally, but why is it faster than #3? Why does #3 not get the same optimization?
What is causing these results? Is there some JIT optimization I might be hitting that skews the data?
More importantly, why is this so drastically different between browsers, with all options being roughly equal in FF?