Apex Performance - String Concat with XML vs ADD
Tue May 14 2024 12:17:47 GMT+0000 (Coordinated Universal Time)
Saved by
@Justus
// Test Config
String strX = 'value';
Integer itr = 100000;
/**
* METHOD 01 Simple String Concat
* Heap Size 24, CPU Time 5803 (100k iterations)
*/
// Add values to the simpleConcatString string
Integer heapStart = limits.getHeapSize();
Integer cpuStart = limits.getCpuTime();
basicConcatMethod('');
Integer cpuEnd = limits.getCpuTime();
Integer heapEnd = limits.getHeapSize();
/**
* METHOD 02 XML StreamWriter Concat Method Cheat
* Heap Size 24, CPU Time 721 (100k iterations)
*/
Integer heapCheatStart = limits.getHeapSize();
Integer cpuCheatStart = limits.getCpuTime();
xmlCheatMethod(new XmlStreamWriter());
Integer cpuCheatEnd = limits.getCpuTime();
Integer heapCheatEnd = limits.getHeapSize();
// Let's run it again with an example usage and also validate the results are the same
Assert.areEqual(
basicConcatMethod(''),
xmlCheatMethod(new XmlStreamWriter())
);
// Add the debugs at the end as we have a huge debug log with 100k iterations
System.debug('');
System.debug('HEAP string concat: ' + (heapEnd - heapStart ));
System.debug('CPUT string concat: ' + (cpuEnd - cpuStart ));
System.debug('');
System.debug('HEAP XML Cheat: ' + (heapCheatEnd - heapCheatStart ));
System.debug('CPUT XML Cheat: ' + (cpuCheatEnd - cpuCheatStart ));
System.debug('');
/**
* Put your concatenation logic in here
*/
static String basicConcatMethod(String input){
for(Integer i =0; i<itr; i++){
input+=strX;
}
return input;
}
/**
* or here
*/
static String xmlCheatMethod(XmlStreamWriter xsw){
for(Integer i =0; i<itr; i++){
xsw.writeCharacters(strX);
}
return xsw.getXmlString();
}
content_copyCOPY
Comments