将数字转换为字符串的“最佳”方法是什么(从速度优势、清晰度优势、内存优势等方面考虑)?
一些例子:
字符串(n) n.toString() “”+n n+“”
将数字转换为字符串的“最佳”方法是什么(从速度优势、清晰度优势、内存优势等方面考虑)?
一些例子:
字符串(n) n.toString() “”+n n+“”
当前回答
在我看来,n.toString()因其清晰性而获得奖励,并且我不认为它会带来任何额外的开销。
其他回答
方法toFixed()也可以解决这个问题。
var n = 8.434332;
n.toFixed(2) // 8.43
如果你好奇哪一个是性能最好的,看看我比较了所有不同的Number ->字符串转换。
看起来2+"或2+""是最快的。
https://jsperf.com/int-2-string
只需使用模板文字语法:
`${this.num}`
是这样的:
var foo = 45;
var bar = '' + foo;
实际上,尽管我这样做是为了简单方便,经过1000次迭代后它看起来是为了原始速度。tostring()有一个优势
请参阅这里的性能测试(不是我写的,而是我自己写的时候发现的): http://jsben.ch/#/ghQYR
基于上面的JSPerf测试的最快速度:str = num.toString();
值得注意的是,当您考虑到它可以在0.1秒内以任何方式进行100万次转换时,速度上的差异并不太显著。
更新:不同浏览器的速度似乎差别很大。在Chrome中num +”似乎是最快的基于这个测试http://jsben.ch/#/ghQYR
更新2:根据我上面的测试,应该注意到Firefox 20.0.1执行. tostring()的速度比“+ num”示例慢了大约100倍。
当使用node.js时,结果似乎类似。我运行这个脚本:
let bar;
let foo = ["45","foo"];
console.time('string concat testing');
for (let i = 0; i < 10000000; i++) {
bar = "" + foo;
}
console.timeEnd('string concat testing');
console.time("string obj testing");
for (let i = 0; i < 10000000; i++) {
bar = String(foo);
}
console.timeEnd("string obj testing");
console.time("string both");
for (let i = 0; i < 10000000; i++) {
bar = "" + foo + "";
}
console.timeEnd("string both");
并得到以下结果:
❯ node testing.js
string concat testing: 2802.542ms
string obj testing: 3374.530ms
string both: 2660.023ms
每次运行的时间都差不多。