What is the difference in memory allocation and performance by using
StringBuilder.Append("Str1");
StringBuilder.Append("Str2");
and
StringBuilder.Append("Str1"+"Str2");
What is the difference in memory allocation and performance by using
StringBuilder.Append("Str1");
StringBuilder.Append("Str2");
and
StringBuilder.Append("Str1"+"Str2");
Ok, I wrote a little test application to time this because you got me interested.
Here's the calculation I used (based off your example).
// Test single appends, going 10,000,000 times.
for (int i = 0; i < 10000000; i++)
_SB1.Append("Test");
// Test append + append going 5,000,000 times.
for (int i = 0; i < 10000000/2; i++)
_SB2.Append("Test" + "Test");
The results (in milliseconds):
First Case (single appends)
77ms
71ms
78ms
73ms
Second Case (Append w/ 2 String +'s)
48ms
61ms
57ms
57ms
So, going half the amount of times, doing the same amount of text, adding strings within an append call is quicker than doing multiple single appends.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.