Nag: Use StringBuilder

Yesterday, I visited MSDN Live here in Stockholm. It was very interesting (as usual). One thing I noted, however, was the reminder not to use string concatenation everywhere, but to use StringBuilder for that task. In my professional life, I have seen a lot of developer disregarding this as well. What was demonstrated at the event, was something like this: string msg = String.Empty; for(int i = 0; i < 10000; i++) { msg += i.ToString(); } Console.WriteLine(msg); Memory Allocation: About 400 Megabyte Garbage Collector: Tired. With StringBuilder: StringBuilder msg = new StringBuilder(); for(int i = 0; i < 10000; i++) { msg.Append(i.ToString()); } Console.WriteLine(msg.ToString()); Memory Allocation: About 400 Kilobyte. Garbage Collector: Happy. 400 megs or 400 kbs ... you pick ;-) Also, check this out: Writing High-Performance Managed Applications : A Primer

Comments

Popular posts from this blog

Auto Mapper and Record Types - will they blend?

Unit testing your Azure functions - part 2: Queues and Blobs

Testing WCF services with user credentials and binary endpoints