I have the following method
void DoSome(){
if (int.Parse(SomeStringProperty) > 8)
// do something
if (int.Parse(SomeStringProperty) < 10)
// do something
}
Does the JIT know to keep the parsed value or is it better to do the following:
void DoSome(){
var x = int.Parse(SomeStringProperty);
if (x > 8)
// do something
if (x < 10)
// do something
}
There is two optimizes the I can see here:
My question its just about the one optimization that will need to be consistent and not about the 2 optimization that can be depending in a lot of factors.
In short, when I write C# app what of the above examples is preferred?
Update
If the answer is not, why its different from this:
foreach (var x in MyMethod.GetEnumeration())
here there no need to do:
var lst = MyMethod.GetEnumeration();
foreach (var x in lst)
In the general case, no. Because: side-effects. In general, any.Method(args)
can do something different every time (logging, randomness, incrementing counters, connecting to an external unmanaged resource, etc), and must be called each time to retain the original semantic. It could be that a white-list of "pure" functions is maintained, but I can think of no special reason to include int.Parse
in that.
Basically, if you want to hoist it: hoist it yourself. The code in your second example is reasonable (personally I'd add an else
, i.e else if
).
Additionally: your example calls SomeStringProperty
multiple times : that too must be called multiple times to retain the semantic, and could behave differently.
Finally, in a multi-threaded world, the field itself could have changed.