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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With