javascript - Best practice with caching. Avoid redundant caching? -


ok question might seem bit basic wonder if should cache variables in functions 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 no real performance gain there? assume apart type safety latter better since need less lines. considered best practice in cases these? should still cache object eventhough not needed?

so unless if statements included:

if(elem.classname == "something") 

i personaly wouldnt bother caching.

at other hand brain in conflict coding style / consistency.

assuming have 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 have cache object due typesafety brings me issue of consistency...

what considered best practice in cases these?

the "best practice" in "such" cases eliminate read(access) operations upon array/object.
in case have 4 read operations both 2 variants.
- avoid multiple read/access operations should save crucial element(reference) local variable
- avoid multiple if else statements - use switch operator instead(it should go faster)
you should consider code readability , code simplicity.
if need "the less lines" - suggest following simple , scalable solution last example:

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

Comments

Popular posts from this blog

ruby on rails - Permission denied @ sys_fail2 - (D:/RoR/projects/grp/public/uploads/ -

c++ - nodejs socket.io closes connection before upgrading to websocket -

java - What is the equivalent of @Value in CDI world? -