简体   繁体   English

索引访问与JavaScript中的变量

[英]Indexed access vs variable in javascript

At various places, an element from array is being used at index. 在各个地方,索引使用数组中的元素。 Instinct says replace it with a variable pointing to that element and use it. 本能说,用指向该元素的变量替换它并使用它。 But is there any other difference than for better readability/management? 但是除了更好的可读性/管理性之外,还有其他区别吗?

Example 1: 范例1:

if (cols[i]["Type"] === 4) {
    this.someFunc(cols[i]["Name"], cols[i]["Value"].VarA, cols[i]["Value"].VarB);
} 

Example 2: 范例2:

var col = cols[i];
if (col["Type"] === 4) {
    this.someFunc(col["Name"], col["Value"].VarA, col["Value"].VarB);
} 

Example 2 will not need to do multiple array lookups so will be slightly faster. 示例2将不需要执行多个数组查找,因此会稍快一些。 That being said, the JIT will most likely hoist that out for you. 话虽这么说,准时制很可能会帮您解决这个问题。

In my opinion Example 2 is more readable and thus easier to maintain, so I would go with that. 在我看来,示例2更具可读性,因此更易于维护,因此我会继续讲下去。

Also as R3tep has stated, you can use col.Type and col.Value.VarA to improve readability further. 同样如R3tep所述,您可以使用col.Typecol.Value.VarA进一步提高可读性。

It would seem to me that referencing the value directly via variable is faster than referencing the value via array element: 在我看来,直接通过变量引用值比通过数组元素引用值要快:

https://jsfiddle.net/cLf7k35n/ https://jsfiddle.net/cLf7k35n/

var test = 4;
var myArray = [0, 1, 2, 3, 4];

console.time("array_reference");
if (myArray[4] === 4) {
  console.log(myArray[4]);
}
console.timeEnd("array_reference");

console.time("variable_reference");
if (test === 4) {
    console.log(test);
}
console.timeEnd("variable_reference");

Check the console for the timers. 检查控制台中的计时器。 In the specific, non-complex example I made, the array reference seemed to be at least 1.2 milliseconds slower. 在我制作的特定的非复杂示例中,数组引用似乎至少慢了1.2毫秒。

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

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