Salesforce Performance Concatenating

In the many attempts to optimize performance in Salesforce, sometimes, it's helpful to find a best practice and develop good habits to avoid being forced to refactor later—particularly if there is no additional development effort. Is it better to concatenate a string with multiple statements or with one? Consider the snippets below:

String a = '';
    a += '0';
    a += '1';
    a += '2';
    a += '3';
    a += '4';
    a += '5';
    a += '6';
    a += '7';
    a += '8';
    a += '9';
                    
String a = ''
    + '0'
    + '1'
    + '2'
    + '3'
    + '4'
    + '5'
    + '6'
    + '7'
    + '8'
    + '9';
                    

The first creates a string, then reassigns the value 10 times in 10 statements. The second is a single statement.

The first takes about 7x as long to run, takes 8x as much cpu time, and has a larger heap size.

If you look at detailed logs, you'll see the first does 10 additional memory allocations.

In .NET, the compiler would optimize this at compile time so that it wouldn't need to be calculated at run-time. We don't have much visibility into how the Apex compiler works, but it appear it might use similar principles.

Running this code has the same costs as our second code snippet:

String a = '0123456789';

If however, I add variables to the string, I'll see the cost go up.

String b = '5';
String a = ''
    + '0'
    + '1'
    + '2'
    + '3'
    + '4'
    + b
    + '6'
    + '7'
    + '8'
    + '9';
                    

In this case the performance is a bit less due to the variable in the middle.

 

 

© 2001 – 2023 Object Factory Inc
marker marker marker marker marker