Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between" if(condition) int++" and int += "Convert.Toint32(condition)"

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?

like image 435
SuperMinefudge Avatar asked Feb 03 '26 07:02

SuperMinefudge


2 Answers

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.

like image 186
Jeffrey L Whitledge Avatar answered Feb 05 '26 20:02

Jeffrey L Whitledge


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);
like image 45
aquinas Avatar answered Feb 05 '26 20:02

aquinas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!