StringBuilder.Append() vs concatenation

S

Simon

Hi folks,

I'm aware of the fact that using a StringBuilder is more efficient than
constantly reassigning a string. For example.

Example A
---------
SringBuilder sb = new StringBuilder();
sb.Append("Some text");
sb.Append(" and some more text");

is more efficient than

Example B
---------
string myString = "Some text";
myString += " some more text";

But what about this.

Example C
---------
StringBuilder sb = new StringBuilder();
sb.Append("Variable = " + myVar + " and that's that.");

vs.

Example D
---------
StringBuilder sb = new StringBuilder();
sb.Append("Variable = ");
sb.Append(myVar);
sb.Append(" and that's that.");

I'm thinking that the concatenation in the Example C does not have the
same overhead as the reassignment in Example B and therefore Example D
is overkill, but I'm prepared to be corrected.

Cheers

Simon
 
V

Vadym Stetsyak

sb.Append("Variable = " + myVar + " and that's that.");
has concatenation the operation inside brackets is the same as Example B

so the most efficient will be Example D.
 
S

Simon

Ok,

I remember reading some time ago that

var = "This" + " is" + " a" + " test";

does not have same issues as

var = "This";
var += " is";
var += " a";
var += " test";

Hence my question. I can see where your coming from on a conceptual
level and how it would reduce down to the same tokens, just confused as
I had read the contrary before.

I take it that this was wrong.

Cheers

Simon
 
J

Jon Skeet [C# MVP]

Simon said:
I remember reading some time ago that

var = "This" + " is" + " a" + " test";

does not have same issues as

var = "This";
var += " is";
var += " a";
var += " test";

Well, there are two issues there.

1) The first is actually a constant, so it becomes exactly equivalent
to:

var = "This is a test";

2) Even with variables, it would be one concatenation call, without
intermediate strings being constructed.

See http://www.pobox.com/~skeet/csharp/stringbuilder.html for more
information.
 
S

Simon

Yup I get ya Jon. Not the best example of what I was thinking. I've read
the article. All is clear.

Many thanks

Simon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top