简体   繁体   中英

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:

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

Example 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. 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.

Also as R3tep has stated, you can use col.Type and col.Value.VarA to improve readability further.

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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