StringBuilder vs basic string Concatenation

So I always hear that StringBuilder is the better, more efficient option… but is that true? How much more efficient is it? Is it worth it?

So lets say I have a method that returns a greeting. With old-school concatenation I can write something simple, and clear:

string _myName = "Bob"; public string GetGreeting(personName) { return "Hello " + personName+ ", my name is " + _myName + "!"; } 

With StringBuilder I have to do something much more space-consuming, which in turn is less clear.

string _myName = "Bob"; public string GetGreeting(personName) { StringBuilding myString = new StringBuilder("Hello "); myString.Append(personName); myString.Append(", my name is "); myString.Append(myName); myString.Append("!"); return myString.ToString(); } 

To me, the second example is the worse code. It's harder to read, it took up more space, and it looks like it does far more work — considering I had to convert myString back to .ToString() (although looks can be decieving) — so is it always best to use StringBuilder?

(I'm a lone programmer at my shop so I don't have anyone to gather opinions from. Just web articles and you guys… really appreciate the help. I'm trying to be a better developer)

by irtehawesome via /r/csharp

Leave a Reply