Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中将数字转换为字符串的最佳方法是什么?(What's the best way to convert a number to a string in JavaScript?)

What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc) ?(将数字转换为字符串的“最佳”方法是什么(就速度优势,清晰度优势,内存优势等而言)?)

Some examples:(一些例子:)

  1. String(n)

  2. n.toString()

  3. ""+n

  4. n+""

  ask by Pacerier translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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倍。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...