开发者

Does a begin-end block affect the performance of a conditional statement?

I am working with Delphi. Does it make any difference in performance if we write if condition in different ways? 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 just because it looks better than the first one.


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

An aspect that might be more important than that the second option looks nicer, is that it is better for maintainence. If you need to add another statement in the else block, you will not accidentally forget to add the begin and end, which would put the statement outside the if and always be executed.


This will not make a difference in performance.

begin and end tell the compiler where a block of code starts and finishes, but no computation needs to be done there.


Begin and End do not slow down your code, as others have already said. I am writing another answer to encourage you even more explicitly to ALWAYS use begin and end whenever you could use them.

It is good to be liberal with using Begin and End, and not worry about them slowing you down (because they don't).

If you go the other way, and leave out begin and end wherever you can, you get into a different type of trouble.

This has happened to me lots. You can get in trouble when you insert a line into a place where no begin and end statement exist. You then end up scratching your head wondering what you did that broke your code. Begin-end-everywhere, even where not needed, is standard operating procedure for a lot of Delphi coders.


The only thing you should keep in mind about if-elseif-else is to keep the common cases up in your code before edge cases, so that the least possible conditions are evaluated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜