1

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

2
  • 2
    The test doesn't show anything, because it doesn't work properly. You should put the initialisation in the initialisation block, and don't loop the code that should be measured. The test engine does the looping. Commented Apr 11, 2015 at 21:45
  • if you don't capture the output, there's no way to tell that the JS core is not cheating and skipping out on work you expect it to do. Commented Apr 12, 2015 at 0:01

2 Answers 2

3

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.

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

Comments

0

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.

Comments

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.