Reputation: 13
My understanding of the engine is that when it comes to literals, it will actually instantiate a new temporary object whenever a method is called on the literal.
So either my understanding is wrong, or the result needs an explanation: http://jsperf.com/literal-vs-object-231
Upvotes: 1
Views: 135
Reputation: 664307
it will actually instantiate a new temporary object whenever a method is called
Well, yes, that's how method calls on primitive values are specified. However, it is used only to explain the behaviour (as it's a simple way to describe how the lookup of properties should end up on the native prototypes), not to tell how it is actually implemented (a static acess to String.prototype
, no temporary object involved).
Why is a string-literal faster than a String-object?
So what does an engine do with string literals? They're constants. Their type is known. A property access - we know what happens. Wait, does anyone do anything with the results? Why call a side-effect free function at all?
You see where this leads to: optimisation. Don't be fooled by the compiler on microbenchmarks.
Upvotes: 3
Reputation: 33163
Browsers can and will optimize native string methods. Calling String.toUpperCase()
is faster on a literal because the JS engine is smart enough to just provide the uppercase string and not do the unnecessary coersion.
If you provide a custom method invoking it is faster on the object, at least on Chrome (this depends highly on the JS engine), because the engine doesn't have an optimization strategy for it. See http://jsperf.com/literal-vs-object-231/2.
Upvotes: 0