Managing better strings

String manipulation is a common operation in any application. Throughout the sales force application you have been using the + operator to concatenate strings. The String class is immutable. This means that each time you concatenate strings in the preceding fashion it creates a new string object. This can lead to inefficient memory utilization (and more work for the garbage collector).

You can improve the memory utilization of strings in your application using the StringBuilder class. Let's take a look at the performance differences between these two methods shown next. Create a new form and place two buttons on the form. Write the following code in the click event of the two buttons:

private void btnStringConcat_Click(object sender, EventArgs e) {

MessageBox.Show("Done!");

private void btnStringBldr_Click(object sender, EventArgs e) {

StringBuilder _temp = new StringBuilder();

_temp.Append("test");

MessageBox.Show("Done!");

The first function in the preceding code performs 10,000 string concatenations while the second function uses the StringBuilder to perform 10,000 appends. Run the application and click on the first button (btnStringConcat). After that, close the form. A .stat file will be generated in the root folder of the mobile device. Take note of the following counters (which show the amount of string objects allocated, their size in bytes, and so on).

Managed String Objects Allocated 10027

Bytes of String Objects Allocated 400140456

Garbage Collections (GC) 438

Bytes Collected By GC 407222100

Now run the same application again and click the second button (btnstringBldr). Another .stat file will be generated. Now take note of this second set of counters.

Managed string Objects Allocated 3 9

Bytes of string Objects Allocated 262584

Garbage Collections (GC) 1

Bytes Collected By GC 296332

The first thing you will immediately notice is that with the stringBuilder class, fewer managed string objects are allocated. The size of the allocated objects is also much smaller. This equates to less memory traffic. It is, therefore, a good idea to use the stringBuilder class whenever possible for strings that change frequently.

Was this article helpful?

0 0

Post a comment