Reputation: 14099
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".
Upvotes: 0
Views: 66
Reputation: 458
It is fine to set a variable to something it might already be set to.
foo = "foo";
Upvotes: 0
Reputation: 46647
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 foo
if it didn't already have a value, you could use the logical or (||
) to do that:
var foo;
// ... some code that may initialize foo ...
foo = foo || 'someDefault';
Beware that this will also default foo
if it has any "falsey" value: 0
, empty string, NaN
, null
, undefined
, or false
. If those values are acceptable then you'd want to use typeof
with a tertiary statement instead:
var foo;
// ... some code that may initialize foo ...
foo = typeof foo === 'undefined' ? 'someDefault' || foo;
Upvotes: 2