Skip to content

Instantly share code, notes, and snippets.

@jdcrensh
Created May 6, 2016 17:51
Show Gist options
  • Save jdcrensh/25cc0573980918d16e6d5ade20a1c71a to your computer and use it in GitHub Desktop.
Save jdcrensh/25cc0573980918d16e6d5ade20a1c71a to your computer and use it in GitHub Desktop.
Profiling of String concatenation and the StringBuilder pattern in Apex (Salesforce)
/**
* Compares String concatenation performance vs StringBuilder.
* At around 21000 iterations, actual time spent is nearly identical. At higher iterations,
* StringBuilder comes out ahead in less actual time spent and with lower CPU usage. However in
* lower iterations, concatenation wins both measurements.
*
* Another consideration is that the StringBuilder pattern does not seem to affect the heap
* size limit at all, which could be a bug with Apex profiling.
*/
final Integer iterations = 21000;
Long start;
/**
* String concatenation
*/
start = System.currentTimeMillis();
String s = '';
for (Integer i = 0; i < iterations; i++) {
s += String.valueOf(i);
}
Long concatTime = System.currentTimeMillis() - start;
/**
* StringBuilder
*/
start = System.currentTimeMillis();
final List<String> strs = new List<String>();
public void append(String str) {
strs.add(str);
}
public String build() {
return String.join(strs, '');
}
for (Integer i = 0; i < iterations; i++) {
append(String.valueOf(i));
}
build();
Long sbTime = System.currentTimeMillis() - start;
/**
* Log time spent
*/
System.debug('');
System.debug('String concat ms: ' + concatTime);
System.debug('StringBuilder ms: ' + sbTime);
System.debug('');
System.debug('concat vs builder: ' + (Decimal.valueOf(concatTime) / Decimal.valueOf(sbTime)).setScale(2) + '%');
System.debug('builder vs concat: ' + (Decimal.valueOf(sbTime) / Decimal.valueOf(concatTime)).setScale(2) + '%');
System.debug('');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment