Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 990
Himadri Avatar asked Jun 30 '10 11:06

Himadri


People also ask

Does if else affect performance?

In general it will not affect the performance but can cause unexpected behaviour. In terms of Clean Code unneserry if and if-else statements have to be removed for clarity, maintainability, better testing. One case where the performance will be reduced because of unnecessary if statements is in loops.

What are the conditional statements in Python?

Decision-making in a programming language is automated using conditional statements, in which Python evaluates the code to see if it meets the specified conditions. The conditions are evaluated and processed as true or false. If this is found to be true, the program is run as needed.

What are conditional statements write the syntax about if statement?

Conditional statements help you to make a decision based on certain conditions. These conditions are specified by a set of conditional statements having boolean expressions which are evaluated to a boolean value of true or false.

Are IF statements Slow?

If-clauses are some of the cheapest operations there are, performance-wise. However, what you put in the if-clause can be really slow. For instance, if (true) { ... } is going to be extraordinarily fast, but a single if (calculatePi()) { ... } is going to take literally forever.


2 Answers

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.

like image 189
Guffa Avatar answered Oct 12 '22 23:10

Guffa


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.

like image 26
Miel Avatar answered Oct 13 '22 00:10

Miel