3

I was running performance benchmarks for jQuery (don't ask) and discovered something interesting. For some reason it seems that this[0] = element is quite slow compared to this.foo = element. Here is the obligatory jsPerf case.

Can anybody explain why there is such a performance hit? Is there any way to improve the performance apart from the obvious "use a string key"?

5
  • could you give us a sense of the difference in performance? (ie, 30% slower vs 100x slower) Commented Oct 12, 2012 at 17:07
  • Some other test jsperf.com/test-string-and-index . I guess the performance hit has to do something with array. Commented Oct 12, 2012 at 17:11
  • Speed is irrelevant if you're using a property that doesn't qualify as a valid identifier. In those cases, you need to use [] irrespective of performance differences. Commented Oct 12, 2012 at 17:14
  • Also, be sure to test in your actual environment instead of just jsPerf. I don't trust it. Commented Oct 12, 2012 at 17:18
  • Property that doesn't qualify as valid identifier will cause very bad performance hit on Chrome. Fun thing is there is almost no difference on IE. Commented Oct 12, 2012 at 17:48

1 Answer 1

2

The [0] has to be found to be incompatible, cast to a string ("0"), and then used as a string lookup ["0"].

I don't know that it explains 100% of what's going on, but that's the universal part, anyway.
Most of the rest would be under-the-hood optimizations, on a per-engine basis.

This is also not an array, nor an array-lookup.
It's just bracket-notation on an object.

Sign up to request clarification or add additional context in comments.

2 Comments

But on an array [0] is faster than ['0']: jsperf.com/string-integer-property/5.
That's because it's an array. Arrays use integers and objects use strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.