LoginSignup
40
25

More than 5 years have passed since last update.

javascript 数値→文字列の変換は + '' が速い

Last updated at Posted at 2016-02-19

数値を文字列にする。
当たり前のように toString() を使っていたら神様に言われました。
「数値を文字列にするだけなら空文字足した方が早いぞ小童」

1億回ずつ測定してみた。

var num=123, i, times=100000000;

console.time('+ \'\'');
for (i = 0; i < times; i++) {
    num + '';
}
console.timeEnd('+ \'\'');

console.time('toString()');
for (i = 0; i < times; i++) {
    num.toString(10);
}
console.timeEnd('toString()');

console.time('String()');
for (i = 0; i < times; i++) {
    String(num);
}
console.timeEnd('String()');

結果:

+ '': 284ms
toString(): 843ms
String(): 1252ms

ほんとだ、はゃぁ!! :flushed:

真偽値(boolean型)でも同様の結果が出るかと思って、試してみた。

結果:

+ '': 3524ms
toString(): 1629ms
String(): 1288ms

逆転したっ!!? :scream:

40
25
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
25