5

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()?

7
  • I'd expect that the overhead of a function call that has to look up to the Number prototype is slower than the built-in string concatenation overloading of the plus operator. Commented Feb 17, 2013 at 7:10
  • 3
    And yes, it is perfectly valid, though you should consider readability more important than a microsecond in your script's execution time. Commented Feb 17, 2013 at 7:15
  • @FabrícioMatté AFAIK all of Java programmers use boo + ""! Do you think it's not human readable? Commented Feb 17, 2013 at 7:17
  • @Afshin, can you determine at first glance that's a conversion to string? Commented Feb 17, 2013 at 7:17
  • 2
    The benchmark results are probably distorted due to certain runtime optimization techniques that can be used as the repetitive operation always yields the same result. You may want to try this benchmark instead. Commented Feb 17, 2013 at 7:38

1 Answer 1

5

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.

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

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.