简体   繁体   English

W3C JavaScript for循环风格

[英]W3C JavaScript for loop style

I was looking through the W3C Javascript Best Practices and I noticed that they write their for-loops in a different way. 我正在浏览W3C Javascript最佳实践 ,我注意到他们以不同的方式编写了for-loops。

var f = document.getElementById('mainform');
var inputs = f.getElementsByTagName('input');
for(var i=0,j=inputs.length;i<j;i++){
  if(inputs[i].className === 'mandatory' &&
     inputs[i].value === ''){
    inputs[i].className += ' error';
  }
}

They assign the inputs length value to j and then compare j with i. 它们将输入长度值分配给j,然后将j与i进行比较。 Instead of just directly comparing inputs.length with i. 而不是直接将inputs.length与i进行比较。 They don't do that everywhere in the guide just in some places. 他们在某些地方的指南中并没有这样做。 Is there a reason other than a preference for writing a for-loop this way? 除了偏好以这种方式编写for循环之外,还有其他原因吗?

Slight performance improvement. 性能略有提升。

Instead of reading length property from array again after each iteration, use cached version. 而不是在每次迭代后再次从数组中读取length属性,而是使用缓存版本。

This will be very very small amount of time that this can be ignored for moderate sized arrays. 对于中等大小的阵列,这可以是非常小的时间。

As I mentioned here , it's a performance thing. 正如我在这里提到的,这是一个表演的事情。 Referencing inputs.length would be a runtime attribute lookup in a hash table at the top of every loop iteration. 引用inputs.length将是每个循环迭代顶部的哈希表中的运行时属性查找。 Caching it in a local variable avoids that, and the results can be dramatic, especially on an interpreter that doesn't have JIT compilation. 在局部变量中缓存它可以避免这种情况,并且结果可能非常显着,尤其是在没有JIT编译的解释器上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM