Skip to main content

Apex switch statement under the microscope

It is almost 18 months since Salesforce finally introduced one of the most eagerly anticipated features for Apex - switch statement. Does it even make sense to comment it today? I can only guess it was because of general familiarity with the switch statement, good documentation or simply happiness over surprising birth of a son you stopped dreaming about years ago, but no one has ever questioned it!

Why do we love switch statements?

We've had switch statements in other programming languages since the dawn of time and if not, it was definitely long before I was born. Therefore reasons to use switch statements over if and if else statements are also clear and kind of indisputable.

It is preferable to use switch, if you can agree with following statements in your programming language and of course specific situation you are in:

  • Code is easier to read and therefore it is easier to understand and maintain
  • Code is easier to debug
  • Code is faster to execute

Switch statement in Apex

I think we can safely say, that syntax of switch statement gives you a lot of opportunities to improve readability of your code. Same applies to debugging.

We can all agree, that this:

switch on genre {
   when COUNTRY {
       jukebox.addToQueue('Johnny Cash', 'Ring of Fire');
   }
   when ROCK, PUNK, GRUNGE {
       jukebox.addToQueue('Nirvana' ,'Smells Like Teen Spirit');
   }
   when else {
       throw new JukeboxProvider.JukeboxProviderException('I dont\'t listen to hip hop.');
   }
}

is more readable than this:

if (genre == JukeboxProvider.Genre.Country) {
   jukebox.addToQueue('Johnny Cash', 'Ring of Fire');
} else if (genre == JukeboxProvider.Genre.Rock || genre == JukeboxProvider.Genre.PUNK || genre == JukeboxProvider.Genre.GRUNGE) {
    jukebox.addToQueue('Nirvana' ,'Smells Like Teen Spirit');
} else {
     throw new JukeboxProvider.JukeboxProviderException('I dont\'t listen to hip hop.');
}

And I don't have to say, that I could have figured out something way more complicated.

Is it fast enough, when I use it well enough?

Performance of switch statement depends on its implementation in specific programming language. Naturally... Switch statement is generally considered to be faster than if and if else statements, because of optimization techniques like branch table or binary search.

And how fast is it specifically in Apex? When I tried out switch right after the release, results of benchmarks I performed looked terrible. It was complete disaster, because if and if else statements were twice as fast. From that point I was using switch only outside of loops and in situations, where importance of readability overwhelmed performance.

I will never know, if Salesforce improved performance of switch statement that much, or I did terrible job and messed up my tests back then, but today situation is different.

Benchmarks

Let's test performance of if, if and if else and switch statements on an expression first. (And before you jump with anger, I know there is something very wrong with the following code.)

//SWITCH STATEMENT
Integer maxIterations = 50000;
 
for (Integer i = 0; i < maxIterations; i++) {
    switch on Math.mod(i,5) {
        when 1 { 
        }
        when 0, 2 { 
        }    
        when else { 
        }
    }   
}

// IF AND IF ELSE
Integer maxIterations = 50000;
 
for (Integer i = 0; i < maxIterations; i++) {
    if (Math.mod(i,5) == 1) {
    } else if (Math.mod(i,5) == 0 || Math.mod(i,5) == 2) {
    } else {
    }
}

// IF
Integer maxIterations = 50000;
 
for (Integer i = 0; i < maxIterations; i++) {
    if (Math.mod(i,5) == 1) {
    }
    if (Math.mod(i,5) == 0 || Math.mod(i,5) == 2) {
    }
    if (Math.mod(i,5) == 3 || Math.mod(i,5) == 4) {
    }
}

I have run these lines at least 10 times and averaged the results.

SWITCH:         4414.667 ms
IF AND IF ELSE: 8233 ms
IF:             13813.667 ms

Switch statement looks like a clear winner, but we have committed a foul here! Modulo is expensive operation and we have performed that multiple times unnecessarily. Let's optimize the code and try it again.

// SWITCH STATEMENT
Integer maxIterations = 50000;
 
for (Integer i = 0; i < maxIterations; i++) {
    Integer j = Math.mod(i,5);
    switch on j {
        when 1 { 
        }
        when 0, 2 { 
        }    
        when else { 
        }
    }   
}

// IF AND IF ELSE
Integer maxIterations = 50000;
 
for (Integer i = 0; i < maxIterations; i++) {
    Integer j = Math.mod(i,5);
    if (j == 1) {
    } else if (j == 0 || j == 2) {
    } else {
    }
}

// IF
Integer maxIterations = 50000;
 
for (Integer i = 0; i < maxIterations; i++) {
    Integer j = Math.mod(i,5);
    if (j == 1) {
    }
    if (j == 0 || j == 2) {
    }
    if (j == 3 || j == 4) {
    }
}

SWITCH:         5370.625 ms
IF AND IF ELSE: 5034.375 ms
IF:             5432.125 ms

Does it mean if and if else is faster than switch? No! Another foul! We don't have to assign statement to another variable – we can put it straight into switch. OK, let's get it right this time. (Next race is just between switch and if and if else. If lost completely last benchmark.)

// SWITCH
Integer maxIterations = 50000;
 
for (Integer i = 0; i < maxIterations; i++) {
    switch on Math.mod(i,5) {
        when 1 { 
        }
        when 0, 2 { 
        }    
        when else { 
        }
    }   
}

// IF AND IF ELSE
Integer maxIterations = 50000;
 
for (Integer i = 0; i < maxIterations; i++) {
   Integer j = Math.mod(i,5);
   if (j == 1) {
   } else if (j == 0 || j == 2) {
   } else {
   }
}

SWITCH:         4235.625 ms
IF AND IF ELSE: 5313.375 ms‬

Alright, this goal is allowed, no foul this time! I have actually tried similar benchmarks in more situations, for example using Enum or having more when blocks. Results were as conclusive as the last one here. The speed difference between switch and if and if else is really negligible and I doubt it will ever influence performance of any org, but still switch is slightly faster.

Looking for an experienced Salesforce Architect?

  • Are you considering Salesforce for your company but unsure of where to begin?
  • Planning a Salesforce implementation and in need of seasoned expertise?
  • Already using Salesforce but not fully satisfied with the outcome?
  • Facing roadblocks in your Salesforce implementation and require assistance to progress?

Feel free to review my profile and reach out for tailored support to meet your needs!

Comments

About author

My photo
Jan Binder
Experienced Salesforce Technical Architect and Team Lead with a proven track record of delivering successful enterprise projects for major global companies across diverse industries, including automotive, oil & gas, and construction.