If I want to give a variable a value that it has a decent chance of already having, should I check whether it does and avoid unnecessary overwriting, or should I just do it and avoid the check? So (using JavaScript here), which option is less work for the processor:
foo = "foo"; //foo might already be set to "foo"
or
if(foo != "foo") {
foo = "foo";
}
Two things to note here: first, while I’m working in JavaScript at the moment, I’d be interested in answers for other languages if they’re different; and second, I will most probably be working with strings that are a lot longer than “foo”.
Simple assignment is always going to be less costly than a condition check. That being said, this is so micro that it really does not matter.
In the case of something a little more complicated like if you only wanted to assign something to
fooif it didn’t already have a value, you could use the logical or (||) to do that:Beware that this will also default
fooif it has any “falsey” value:0, empty string,NaN,null,undefined, orfalse. If those values are acceptable then you’d want to usetypeofwith a tertiary statement instead: