Does an entry-level block affect the performance of a conditional statement?

I work with Delphi. Is there a difference in performance if we write if condition differently? For example:

 if (condition) then someVar := someVal else someVar := someOtherVal; 

Or we can write:

 if (condition) then begin someVar := someVal; end else begin someVar := someOtherVal; end; 

I prefer the second option only because it looks better than the first.

+6
performance syntax if-statement delphi
source share
4 answers

No, there is no difference in performance, the generated code will be identical.

The aspect, which may be more important than the second option, looks more enjoyable, is that it is better supported. If you need to add another statement in the else block, you will not accidentally forget to add a beginning and an end, which puts the statement outside the if and will always be executed.

+21
source share

This will not affect performance.

begin and end tell the compiler where the code block begins and ends, but no calculations are needed here.

+3
source share

The only thing you should remember is that if-elseif-else is to keep the usual cases in your code before the extreme cases, so that the smallest possible conditions are evaluated.

+1
source share

The beginning and the end do not slow down your code, as others have said. I am writing another answer in order to even more explicitly recommend ALWAYS use the beginning and the end whenever you can use them.

It’s good to be liberal with Begin and End, and not worry that they slow you down (because they don’t).

If you go the other way and leave the beginning and the end, wherever you are, you are faced with various problems.

It happened to me a lot. You may have problems when you insert a string in a place where there are no start and end statements. Then you end up scratching your head, thinking what you did that broke your code. Start-end - everywhere, even if it is not required - is the standard procedure for many Delphi codecs.

+1
source share

All Articles