At times I have needed to concatenate thousands of small strings in PeopleCode—for example, to build the huge grid mentioned
in my last post on HTML areas and server communication. That grid, an HTML table written to an HTML area on the page,
contained thousands of cells. The usual way to build up a string is to simply say &x = &x | &y . Unfortunately, this type of concatenation can become very
slow and inefficient, to the point that it becomes noticeable to the user.
A fairly surprising way around this is suggested by PeopleBooks in at least two places: The API Reference (Array class, Join method) and the
PeopleCode Developer's Guide ("Writing More Efficient Code"). The idea is to use a huge array, fill it with all of the strings to be concatenated
using .Push(),
and then .Join() them together once at the end to get the final string. It may be difficult to believe that with the overhead of the array this would make
this process more efficient, but look at these sample timings from concatenating large numbers of 10-character strings:
Strings
String Method
Array Method
20,000
2.4 sec
0.1 sec
40,000
9.4 sec
0.1 sec
60,000
21.3 sec
0.2 sec
80,000
38.2 sec
0.2 sec
100,000
59.6 sec
0.3 sec
When we use normal concatenation, each step apparently creates a new destination string, copies the old contents (plus the new piece) into that new
string, and destroys the old string. This is not necessary when we are just putting a string into an array. In that method, the destination string
is created only once instead of thousands of times.
I created an App Package class similar to the PeopleBooks example and now use it frequently.