Pages

Thursday, August 11, 2011

Using StringBuilder for string concatenation

It is being said that you should always use StringBuilder object to append strings. But you can simply do the same thing using an overloaded + or += operator. Once you compile the program, compiler will tranform the + operator to String.Concat.

So why we should use StringBuilder?

The reason is String is an immutable object, which means if you create a string once you cannot change it again. So, if you keep appending several strings, it will create lot of unnessasary temporary strings in memory.
To clean them up, garbage collection needs to run more often - resulting an additional overhead.

Unlike String, StringBuilder is mutable, so it will reduce the no of temporary objects you create in memory.
Consequently, it will make appending faster than the String.

No comments:

Post a Comment