Do you optimize too much?

Ever see some code and think “I could rewrite that tighter and cleaner“ but when you do so, you wonder if you’ve actually improved anything or just made it harder to understand at first glance?

In the two examples below, both chunks of code end up doing the same thing. So… while option 1 is more intuitive (to me at least) than option 2, I couldn’t help but wonder if this was strictly a matter of personal style and preference, or was there a potential performance difference in doing one way vs the other? For example, in option 2 you are potentially doing two assignment operations, etc…

If expression Then
myVar = myObject.property
Else
myVar = myControl.Text
End If

…OR…

myVar = myControl.Text
If expression Then myVar = myObject.property

So I did a little experimenting, ran the code a few bajillion times and found out that it actually is faster to use option one, in spite of the fact that it takes more lines of code. so now you know… and of course, option 1 also has the added bonus of being more obvious to the next guy who comes along to maintain your code. In many cases, that’s more important (to me) than the potential performance boost (unless it’s a big one)

Tinggalkan komentar