Sunday, 9 December 2012

When performance matters: string concat



Due to the memory optimization in the StringBuilder class, the concatenation of strings can be 10 times faster or more than using the “+” operator of strings.
One of the reasons the + operator for strings is not the fastest way to perform this operation is because it does not actually conctatenetes two strings at the same time but allocates a new memory space for the previous stirng “Plus” the new one. That is say:

Text = “Hello”

This means the memory allocated an array of chars with the following content:
Memory Address X à{‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’}

However, when we perform the following operation:
Text += “, world.”

This time, the memory will look like follows:
Memory Address X à{‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’}
Memory Address Y à{‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘,’, ‘ ’, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’, ‘\0’}

The original string is kept in its orginal memory position while the concat operation allocated a new memory space to put the new resulting string.

On the other hand, the StringBuilder class has an optimized use of memory allocation. As a result, it improves the Append algorithm by extenteding the allocated memory.
StringBuilder sb = new StringBuilder();
sb.Append(“Hello”);
Memory Address X à{‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’}
sb.Append(“Hello, world”);
Memory Address X à{‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘,’, ‘ ’, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’, ‘\0’}

As a result, due to the better memory management of the StringBuilder class when concatenating strings, this is the best way to address any performance issue when concatenating.


No comments:

Post a Comment