Javascript字符串长度是恒定时间吗? [英] Is the Javascript String length constant time?

查看:79
本文介绍了Javascript字符串长度是恒定时间吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JS很新,并且认识到长度被视为属性。但我收到一条评论,不在循环中使用str.length:

I'm fairly new to JS, and realize length is considered a property. But I received a comment to not use str.length in a loop:

for(i = 0; i< str.length; i ++) {...}

vs

var len = str.length;
for (i=0; i<len; i++){...}

现在,我知道str.length()是Java中的常量时间操作,因为长度存储为String类中的字段。但话说回来,字符串在Java中是不可变的。
虽然我不确定JS字符串。 str.length是否也保证了JS中的常量时间?无法在网络的任何地方找到这个。

Now, I know str.length() is constant time operation in Java because length is stored as a field in String class. But then again, strings are immutable in Java. I am not sure about JS strings though. Is str.length guaranteed constant time in JS too? Couldn't find this discussed anywhere in the web.

推荐答案

字符串在JavaScript中也是不可变的。每次访问时都不需要计算 length 属性。

Strings are also immutable in JavaScript. The length property does not need to be computed each time it is accessed.

我创建了一个 jsperf基准供你在这里查看。

I created a jsperf benchmark for you to view here.

你会注意到速度是一样的。

You'll notice the speeds are the same.

这篇关于Javascript字符串长度是恒定时间吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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