like this:(像这样:)
var foo = 45;
var bar = '' + foo;
Actually, even though I typically do it like this for simple convenience, over 1,000s of iterations it appears for raw speed there is an advantage for .toString()
(实际上,即使我通常这样做是为了简单方便,但对于原始速度而言 ,似乎出现了1000多次迭代,但.toString()
还是有优势的)
See Performance tests here (not by me, but found when I went to write my own): http://jsben.ch/#/ghQYR(请参阅此处的性能测试(不是我自己的,而是在我自己编写时发现的): http : //jsben.ch/#/ghQYR)
Fastest based on the JSPerf test above: str = num.toString();
(基于上面的JSPerf测试最快: str = num.toString();
)
It should be noted that the difference in speed is not overly significant when you consider that it can do the conversion any way 1 Million times in 0.1 seconds .(应该注意的是,当您认为速度差异可以在0.1秒内进行1百万次转换时,速度差异并不是太大。)
Update: The speed seems to differ greatly by browser.(更新:速度因浏览器而异。)
In Chrome num + ''
seems to be fastest based on this test http://jsben.ch/#/ghQYR(在Chrome num + ''
,根据此测试,似乎是最快的http://jsben.ch/#/ghQYR)
Update 2: Again based on my test above it should be noted that Firefox 20.0.1 executes the .toString()
about 100 times slower than the '' + num
sample.(更新2:再次根据我上面的测试,应该注意到Firefox 20.0.1执行.toString()
速度比'' + num
示例慢大约100倍。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…