Hay Dear!
i know that if statement is an expensive statement in c++. I remember that once my teacher said that if statement is an expensive statement in the sense of computer time.
Now we can do every thing by using if statement in c++ so this is very powerful statement in programming perspective but its expensive in computer time perspective.
i am a beginner and i am studying data structure course after introduction to c++ course.
my Question to you is
Is it better for me to use if statement extensivly?
If statements are compiled into a conditional branch. This means the processor must jump (or not) to another line of code, depending on a condition. In a simple processor, this can cause a pipeline stall, which in layman's terms means the processor has to throw away work it did early, which wastes time on the assembly line. However, modern processors use branch prediction to avoid stalls, so if statements become less costly.
In summary, yes they can be expensive. No, you generally shouldn't worry about it. But Mykola brings up a separate (though equally valid) point. Polymorphic code is often preferable (for maintainability) to if or case statements
I'm not sure how you can generalise that the if statement is expensive.
If you have
if ( true ) { ... }
then this the if
will most likele be optimised away by your compiler.
If, on the other hand, you have..
if ( veryConvolutedMethodTogGetAnswer() ) { .. }
and the method veryConvolutedMethodTogGetAnswer()
does lots of work then, you could argue tha this is an expensive if statement but not because of the if, but because of the work you're doing in the decision making process.
"if"'s themselves are not usually "expensive" in terms of clock cycles.
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