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

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -