将数字转换为字符串的“最佳”方法是什么(从速度优势、清晰度优势、内存优势等方面考虑)?

一些例子:

字符串(n) n.toString() “”+n n+“”


当前回答

下面是在JS中将Integer转换为String的方法。

这些方法按性能递减的顺序排列。

var num = 1

方法1:

num = `${num}`

方法2:

num = num + ''

方法3:

num = String(num)

方法4:

num = num.toString()

注意:你不能对一个数字直接调用toString()。2.toString()将抛出Uncaught SyntaxError:无效或意外令牌。

(性能测试结果由@DarckBlezzer在他的回答中给出)

其他回答

我们还可以使用String构造函数。根据这个基准测试,它是在Firefox 58中将数字转换为字符串的最快方法,尽管它比Firefox 58慢 + num在流行浏览器谷歌Chrome。

开玩笑的意味很明显:

var harshNum = 108;
"".split.call(harshNum,"").join("");

或者在ES6中,你可以简单地使用模板字符串:

var harshNum = 108;
`${harshNum}`;

对于数字字面值,访问属性的点必须与十进制点区分。如果你想在数字文字123上调用to String(),这留给你以下选项:

123..toString()
123 .toString() // space before the dot 123.0.toString()
(123).toString()

. tostring()是内置类型转换函数,我不是这方面的专家,但每当我们比较内置类型转换和显式方法时,内置的解决方案总是首选。

当使用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

每次运行的时间都差不多。