Good morning,
Say I have a class ClassA
, an operator +
which sums up two objects of type ClassA
, an implicit casting from int
to ClassA
, and that I want to overload the operator ++
... Supposing the code for +
is rather long, but that the sum of a ClassA
and 1
is a very particular case of it, which option is better?
- Implement
++
using+
and the implicit casting already defined. - Repeat part of the code which simplifies alot when adding just
1
.
My idea is that (2) is better since it saves the creation of a new ClassA
object 开发者_运维技巧by the implicit casting, which can be quite useful if the ++
operator is used, for example, in a for
cycle. Also, speed is a must.
Thank you very much.
You've answered your own question. If speed is a must, then go with the second, faster option (it's a good idea to benchmark it to make sure it really is significantly faster though).
Otherwise, go with the first option since less code is better (and staying DRY doubly-so). Less code means less potential bugs, less to maintain, less to write, and less to read. If the code largely duplicates another section of code, then you'd have to keep the two in sync as you make changes -- this would be inviting trouble, as it's easy to forget to update one (and even if you always remember to make changes to both places, since they're not exactly identical it's possible to correctly update one section and incorrectly update the other).
Make sure speed really is a must though before making your final decision -- you don't want premature optimization.
Either way is acceptable. It sounds like the second way is what you're already leaning towards, so try it. In fact, try it both ways and measure the time it takes to increment a million times. Benchmarking is always the way to make these decisions.
In case you haven't done any benchmarking before, the simplest way is to create a System.Diagnostics.Stopwatch and start/stop it around the relevant code. You can then write the elapsed time to a console.
My opinion is that if +1 is a real special case that is much simpler, do the special ++ implementation. You can always comment it out and refer it to + 1 if you want to keep your code small.
Otherwise, it will be too easy to forget about this special optimization 6 mo. down the road when you are trying to optimize.
Premature optimization refers to the fact that you are optimizing before you know how to, not when you have a clear rationale to do so. How to draw the line is difficult, however; you'd need to decide how much simpler the ++ code is in order to consider putting it in.
精彩评论