﻿Do you ever have the desire to optimize your code as much as possible? Do you have any cases where every nanosecond matters? Do you use If statements? This quick tip can help your code run slightly faster with no additional code. We all know that for each command executed, there is a cost associated with it. Re-ordering your If Statements may lead to small performance gains (size of gains will depend on amount of iterations). When using If Statements, putting your most likely case in the IF clause will yield the best performance. This is true because for each additional ElseIf clause that is added, all prior clauses must first be evaluated. Based on my tests, given the following If Statement structure: Clause1...ClauseN-Else. The time to reach Clause1 will be fastest, followed by Clause2, etc... However, this pattern only repeats until ClauseN-1. Else will be slightly faster than ClauseN. It appears that the conditional jump from ClauseN to Else is less expensive than the jump from ClauseN to the end of the If statement, so Else is slightly less expensive than ClauseN. **NOTE: See below for the case where N=1.** See the following test case and results: ### When N>1:
``````ClassMethod Run2()
{
For i=1:1:4 {
Set time(i,"start")=\$zh
For j=1:1:1000000 {
If i=1 {
set a=1
} ElseIf i=2 {
set a=1
} ElseIf i=3 {
set a=1
} Else {
set a=1
}
}
Set time(i,"end")=\$zh
}

W "Time for If: ",time(1,"end")-time(1,"start")," seconds",!
W "Time for ElseIf #1: ",time(2,"end")-time(2,"start")," seconds",!
W "Time for ElseIf #2: ",time(3,"end")-time(3,"start")," seconds",!
W "Time for Else: ",time(4,"end")-time(4,"start")," seconds",!
}``````

Time for If: .02166 seconds
Time for ElseIf #1: .026443 seconds
Time for ElseIf #2: .035915 seconds
Time for Else: .032695 seconds

### When N=1:

``````ClassMethod Run()
{
For i=1:1:2 {
Set time(i,"start")=\$zh
For j=1:1:1000000 {
If i=1 {
set a=1
} Else {
set a=1
}
}
Set time(i,"end")=\$zh
}

W "Time for If: ",time(1,"end")-time(1,"start")," seconds",!
W "Time for Else: ",time(2,"end")-time(2,"start")," seconds",!
}``````

Time for If: .02168 seconds
Time for Else: .015388 seconds

Based on these results, In the case where you have IF-Else, you should put your most common case in the Else Block. In the case where you use If-ElseIf-Else, you should put your most common case in the If Block.

As you can see, these numbers are relatively small compared to the 1 million iterations. However, if you are ever writing code that loops millions of times, reordering your If Statements can save you some time.