views:

128

answers:

3

The current value of a variable may be "X" or "Y".

A function needs to make sure it is "X".

In general -- with say C integers-- which is more efficient:

"if not X, then set to X"

"just set it to X anyway"

And does that change when the "value" is an Objective-C (immutable) object that has to get re-created?

And in both cases is this something everyone agrees on, or a debatable matter?

+5  A: 

Just set it anyway would be more efficient, unless X contains some huge amount of data or you're inside a large loop.

Chris S
It also depends on the probability of the different variable values. Which is why I think it’s best to (a) forget about the issue unless you are chasing milliseconds, or (b) profile the code if you are.
zoul
@zoul: I fully support your point but it is probably more an issue of chasing nano- or fractions of microsecond than milliseconds.
Fredrik
Yeh it'll have such a small effect it's not worth worrying about. Unless the data is large then it is - an iPhone gives you 5 seconds to clean and dispose of what you're doing before it forceable kills your process.
Chris S
I wish I could remember who first made this observation: "this is like getting a haircut to lose weight".
Mike Dunlavey
+3  A: 

The performance difference is usually so small that for most people it simply does not matter. I do what “reads better.” If you are in the situation where the difference might matter, profile.

zoul
A: 

Surely if you're dealing with an object the comparison requires invocation of a method.

Therefore you might as well just set it.

Tom Duckering