在JavaScript中将数字转换为字符串的最好方法是什么? [英] What's the best way to convert a number to a string in JavaScript?

查看:233
本文介绍了在JavaScript中将数字转换为字符串的最好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将数字转换为字符串(在速度优势,清晰度优势,内存优势等方面)的最佳方式是什么?




  1. String(n)


  2. n.toString()


  3. + n


  4. n +

    $


    $ b pre> var foo = 45;
    var bar =''+ foo;

    实际上,即使我通常这样做只是为了方便,超过1000次迭代对于原始速度, .toString()



    这里(不是我,但发现当我去写我自己):
    http://jsperf.com / number-to-string / 2



    根据上面的JSPerf测试最快: str = num.toString();



    应该注意的是,当你认为它可以做转换时,速度的差异不是太大



    更新:浏览器的速度似乎有所不同。在Chrome num +''似乎是最快的基于这个JSPerf测试(不同于上面的测试) http://jsperf.com/scunliffe-number-to-string



    更新2:再次基于我上面的测试,应该注意到Firefox 20.0.1执行 .toString()比$ ' 示例。


    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+""

    解决方案

    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://jsperf.com/number-to-string/2

    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 JSPerf test (different than above test) http://jsperf.com/scunliffe-number-to-string

    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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆