Afshin Mehrabani
Afshin Mehrabani

Reputation: 34929

Why concat empty character is faster than .toString()?

I have this code:

var boo = 123123;

I want to convert that number to string and conact string is faster than native JavaScript .toString():

Faster:

var foo = boo + ""; 

Slower:

var foo = boo.toString(); 

jsPerf: http://jsperf.com/concat-string-vs-tostring

Why .toString() is slower than concating empty character? And finally I want to know is that a correct approach to use + "" technique instead of .toString()?

Upvotes: 5

Views: 1239

Answers (1)

Petro Semeniuk
Petro Semeniuk

Reputation: 7038

Results will vary depends on javascript engine used. On chrome one I'm getting the same results as Afshin.

So why actually one is slower than another? It's because on toString there will be one more call to C functions inside V8. You can try next to see that by yourself:

  • Open empty tab in chrome(to avoid any side effects from already opened pages)
  • Open Developers Tools
  • Open Profiles tab and start new profile
  • Go to Console tab and insert script1 script, press enter.
  • Go to Profile again and stop profiling
  • Repeat the same with script2

  • script 1: var boo = 123123; var foo = boo + "";

  • script 2: var boo = 123123; var foo = boo.toString();

In my case first will result in next stacktrace:

  InjectedScript.evaluate
    InjectedScript._evaluateAndWrap

while second one:

  InjectedScript.evaluate
    InjectedScript._evaluateAndWrap
      InjectedScript._evaluateOn
        evaluate

I think it's more has to do with engine internals than official js spec and probably could be optimized to use the same code path.

Upvotes: 5

Related Questions