Asperger Asperger - 6 months ago 31
Javascript Question

Best practice with caching. Avoid redundant caching?

Ok this question might seem a bit basic but I wonder if I should cache variables in functions like these:

function fooBar(target) {
var elem = target.children[0].children[1];

if(n == 1) {
elem.style.color = "red";
}
else {
elem.style.color = "blue";
}
}


vs

function fooBar(target) {
if(n == 1) {
target.children[0].children[1].style.color = "red";
}
else {
target.children[0].children[1].style.color = "blue";
}
}


There is no real performance gain is there? I assume apart from type safety the latter is better since I need less lines. What exactly is considered best practice in cases like these? Should I still cache the object eventhough its not needed?

So unless my if statements included:

if(elem.className == "something")


I personaly wouldnt bother caching.

At the other hand my brain is in conflict with coding style / consistency.

Assuming I have something like this:

function fooBar(target) {
if(n == 1) {
target.children[0].children[1].style.color = "red";
}
if else (n == 2) {
target.children[0].children[1].style.color = "blue";
}
if else (n == 3) {
target.children[0].children[1].style.color = "yellow";
}
else {
target.children[0].children[1].style.color = "green";
}
}


Then I would have to cache the object due to typesafety which brings me back to the issue of consistency...

Answer

What exactly is considered best practice in cases like these?

The "best practice" in "such" cases is to eliminate read(access) operations upon array/object.
In your case you have 4 read operations for both two variants.
- To avoid multiple read/access operations you should save the crucial element(reference) into a local variable
- To avoid multiple if else statements - use switch operator instead(it should go faster)
You should also consider the code readability and code simplicity.
But if you need "the less lines" - I would suggest the following simple and scalable solution for your last example:

function fooBar(target) {
  var styles = ["green", "red", "blue", "yellow"];  // of course, if "n" increases consecutively (can be also transformed into object)  
  target.children[0].children[1].style.color = styles[n] || styles[0];
}