PeterSchroer - Friday, September 29, 2006 8:55 AM:
Last week Peter sent everybody an example of method code where performance was improved from 6 min to few seconds by replacing string concatenation on StringBuilder.Append(…). In fact, the case is a classic example that could be found in many papers on how to write efficient code. To demonstrate the problem I’ve written a tiny program that compares the performance of string concatenation vs. usage of StringBuilder class (see attached *.cs file if interested): the program just concatenates a simple AML in a loop where the loop count is the program argument. So, the results are:
100 loops: String time: 00:00:00; StringBuilder time: 00:00:00
500 loops: String time: 00:00:00.1301872; StringBuilder time: 00:00:00
1000 loops: String time: 00:00:00.6208928; StringBuilder time: 00:00:00
2000 loops: String time: 00:00:02.8340752; StringBuilder time: 00:00:00.0100144
4000 loops: String time: 00:00:12.4078416; StringBuilder time: 00:00:00.0100144
10000 loops: String time: 00:01:19.7847248; StringBuilder time: 00:00:00.0500720
As you can see, time for string concatenation grows exponentially with loop number increase and time spent by StringBuilder on the same operation remains virtually 0. So, when you write Innovator customizations, please follow the simple set of rules:
-
it’s OK to concatenate up to several tens of strings using string concatenation ( ‘&’ in VB; ‘+’ in C#) – it’s a little bit more convenient syntax and the code is a little bit shorter
-
if you have a loop inside which you concatenate a string it could be a good idea to use StringBuilder class for string concatenation. Mostly it depends on what kind of loop is performed: if you loop by item properties, it’s probably OK to still use string concatenation as number of item properties is not that big (probably less then few tens); if you loop over a set of items or result set and build a string that contains information from each item, then you must use StringBuilder as you can’t predict a size of the result set that the code will iterate over.
-AK