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.
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.
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.
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.
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.
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.
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