Reputation: 301
these two ways of incrementing a value by one
if (Condition) int++;
and
int+= Convert.Toint32(Condition);
so is there and benefit to write in one way or another or are they basically the same?
Upvotes: 2
Views: 255
Reputation: 52280
I'm thinking the clarity of the code depends on the context.
For almost all ordinary cases,
if (condition) i++;
...is going to be easier to read.
But there may be some situations like this one where the alternative makes it easier to follow. Imagine if this list were very long:
var errorCount = 0
errorCount += Convert.ToInt32(o.HasAProblem);
errorCount += Convert.ToInt32(o.HasSomeOtherProblem);
errorCount += Convert.ToInt32(p.DoesntWork);
On the other hand, for the above, maybe I'd find a different way of structuring the code entirely, e.g.
var errorFlags = new [] {o.HasProblem,
o.HasSomeOtherProblem,
p.DoesntWork};
var errorCount = errorFlags.Count(a => a);
Also, the construct
i += Convert.ToInt32(condition);
...may result in a cleaner pipeline since there is no branch prediction involved. The key word is may.
Upvotes: 0
Reputation: 11963
There are many many many many ways to write code that does the same thing. But it all comes down to readability and maintainability.
You can choose to write it in binary and you will be able to optimize it in the most efficient way. But you won't find too many ppl able to maintain the code you have written. I bet not even you want to read your own code in binary when there is a bug.
so which way do you want to do it? considering that there is not that much performance gain for the 2nd method, I would say definitely go for the 1st for the sake of ppl who might be reading your code later.
Upvotes: 2
Reputation: 23796
I get 7527ms and 5888ms on my machine from the benchmark below. The first approach (boolean conversion), besides being just awful from a code readability point of view is also slower. That makes sense, that approach has the overhead of ALWAYS 1) performing a conversion from bool to int, and 2) performing an addition operation. Yes, there are probably shortcuts for adding "0", but that's still ANOTHER test that has to be looked at.
int sum = 0;
var sw = Stopwatch.StartNew();
for (int i = 0; i < Int32.MaxValue; i++) {
bool condition = i < Int32.MaxValue / 2;
sum += Convert.ToInt32(condition);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
sum = 0;
sw = Stopwatch.StartNew();
for (int i = 0; i < Int32.MaxValue; i++) {
bool condition = i < Int32.MaxValue / 2;
if (condition) {
sum++;
}
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Upvotes: 3
Reputation: 59513
Adding a Boolean to an integer doesn't make any sense.
Yes, it works, because of the conversion. But it still doesn't make any sense. It's illogical.
Programs should be obvious and clear, not puzzles to be solved.
Upvotes: 8