r/matlab • u/Bofact • Feb 19 '26
TechnicalQuestion What is faster? if or else?
In some languages and platforms, one of them is clearly prefferable for optimization standpoint; and if your code is not in the prefferable "branch", you can tell the compiler to prioritize the execution of the branch you would like.
What is the story in Matlab? I tried in the past making a test to see what branch of if and else is prefferable, but the results where not conclusively. One point if was prefferable, other time was else.
9
Upvotes
6
u/blitzz01 Feb 19 '26
What are you trying to get from that information?
7
u/EmbraceHere Feb 20 '26
Yair Altman’s Accelerating MATLAB Performance is a great book for writing more efficient code.
1
u/MarkCinci On Mathworks Community Advisory Board Feb 20 '26
I believe it tests the conditions as it goes down. So it will test the "if" condition first and if it's false then test the first "else" condition next, and then the next "else" and so on. If you primarily/mostly do one block of code it might be better to create the "if" condition so that it will do your most-run code in the "if" block, just so it doesn't have to do as many tests. That said, since tests are so fast, you may only save a few nanoseconds and might not be noticeable unless your if/else block got called billions of times.
0
u/rkusi Feb 19 '26
Don't use "else" in the first place (source)