Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use StringBuilder? [duplicate]

Possible Duplicate:
String vs StringBuilder

I just revisited some of the books that I used to pick up VB.NET. I am not sure I've got this in my head, understand how/what StringBuilder is.

What is the guidance for using? Is it best to use it if you are are concatenating 2 strings or 50?

Or when the the total string length is greater than 128 characters?

Or will you see a performance benefit whenever you use it to add strings together?

In which case is it better to use a StringBuilder instance to build a SQL statement than string.format("Select * from x where y = {0}",1)?

It's always struck me that declaring another variable and including a name space is not beneficial for small string concatenations, but I am not sure now.

Sorry, lot of documentation tells you what to use, just not what's best.

like image 337
spacemonkeys Avatar asked Feb 09 '09 21:02

spacemonkeys


1 Answers

I've got an article on this very topic. In summary (copied from the bottom of the page):

  • Definitely use StringBuilder when you're concatenating in a non-trivial loop - especially if you don't know for sure (at compile time) how many iterations you'll make through the loop. For example, reading a file a character at a time, building up a string as you go using the += operator is potentially performance suicide.
  • Definitely use the concatenation operator when you can (readably) specify everything which needs to be concatenated in one statement. (If you have an array of things to concatenate, consider calling String.Concat explicitly - or String.Join if you need a delimiter.)
  • Don't be afraid to break literals up into several concatenated bits - the result will be the same. You can aid readability by breaking a long literal into several lines, for instance, with no harm to performance.
  • If you need the intermediate results of the concatenation for something other than feeding the next iteration of concatenation, StringBuilder isn't going to help you. For instance, if you build up a full name from a first name and a last name, and then add a third piece of information (the nickname, maybe) to the end, you'll only benefit from using StringBuilder if you don't need the (first name + last name) string for other purpose (as we do in the example which creates a Person object).
  • If you just have a few concatenations to do, and you really want to do them in separate statements, it doesn't really matter which way you go. Which way is more efficient will depend on the number of concatenations the sizes of string involved, and what order they're concatenated in. If you really believe that piece of code to be a performance bottleneck, profile or benchmark it both ways.
like image 194
Jon Skeet Avatar answered Oct 06 '22 13:10

Jon Skeet