.substr(0,1)或.charAt(0)之间有什么区别? [英] What's the difference between .substr(0,1) or .charAt(0)?

查看:760
本文介绍了.substr(0,1)或.charAt(0)之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们想知道这个 thread 如果使用 .substr(0,1)与使用<$ c之间存在真正的差异$ c> .charAt(0)当你想获得第一个字符时(实际上,它可以适用于你只有一个字符的任何情况)。

We were wondering in this thread if there was a real difference between the use of .substr(0,1) and the use of .charAt(0) when you want to get the first character (actually, it could apply to any case where you wan only one char).

其中每一个都比另一个快吗?

Is any of each faster than the other ?

感谢您的回答!

Max

推荐答案

测量它是关键!

转到 http://jsperf.com/substr-or-charat 自己进行基准测试。

Go to http://jsperf.com/substr-or-charat to benchmark it yourself.

substr(0,1)在我的机器上以每秒21,100,301次操作运行,charAt(0)每秒运行550,852,974次。

substr(0,1) runs at 21,100,301 operations per second on my machine, charAt(0) runs 550,852,974 times per second.

我怀疑是charAt在内部访问字符串作为数组,而不是拆分字符串。

I suspect that charAt accesses the string as an array internally, rather than splitting the string.

如注释中所示,使用string [0]直接访问char比使用charAt(0)稍快一些。

As found in the comments, accessing the char directly using string[0] is slightly faster than using charAt(0).

这篇关于.substr(0,1)或.charAt(0)之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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