0

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);
} 
5
  • Example 2 will be slight faster, using cached version. Commented Apr 12, 2016 at 15:23
  • You can write col.Value.VarA. You win 3 caracters Commented Apr 12, 2016 at 15:25
  • if you want to improve readability use dot notation Commented Apr 12, 2016 at 15:25
  • 1
    @Tushar For that kind of optimization, the compiler will likely take care of it anyway. There's probably 0 runtime difference. Commented Apr 12, 2016 at 15:27
  • @JosephMarikle other than the first pass, trivial in this case but worth noting. Commented Apr 12, 2016 at 15:31

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Forked your fiddle to include variable assignment and ran the tests. On average, it was 3 times faster on average to do via variable. jsfiddle.net/p0cj3tzg
1

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.

1 Comment

Your answer is relevant too, but the other answer provided an example to test. Thanks for your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.