在 JavaScript 中将数字转换为字符串的最佳方法是什么? [英] What's the best way to convert a number to a string in JavaScript?
问题描述
将数字转换为字符串的最佳"方法是什么(在速度优势、清晰度优势、内存优势等方面)?
一些例子:
String(n)
n.toString()
""+n
n+""
像这样:
var foo = 45;var bar = '' + foo;
实际上,尽管我通常这样做是为了简单的方便,但在超过 1,000 次的迭代中看起来对于原始速度来说 .toString()
在这里查看性能测试(不是我自己做的,而是我自己写的时候发现的):http://jsben.ch/#/ghQYR
最快基于上面的JSPerf测试:str = num.toString();
应该注意,当您考虑到它可以在任何方式下0.1 秒内进行 100 万次转换时,速度的差异并不过分显着..>
更新:速度似乎因浏览器而异.在 Chrome 中 num + ''
基于这个测试似乎是最快的 http://jsben.ch/#/ghQYR
更新 2: 再次基于我上面的测试,应该注意到 Firefox 20.0.1 执行 .toString()
比 慢大约 100 倍'' + num
示例.
What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc) ?
Some examples:
String(n)
n.toString()
""+n
n+""
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()
See Performance tests here (not by me, but found when I went to write my own): http://jsben.ch/#/ghQYR
Fastest based on the JSPerf test above: 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.
Update: The speed seems to differ greatly by browser. In Chrome num + ''
seems to be fastest based on this test 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.
这篇关于在 JavaScript 中将数字转换为字符串的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!