Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it worth using StringBuilder in web apps?

In web app I am splitting strings and assigning to link names or to collections of strings. Is there a significant performance benefit to using stringbuilder for a web application?

EDIT: 2 functions: splitting up a link into 5-10 strings. THen repackaging into another string. Also I append one string at a time to a link everytime the link is clicked.

like image 714
zsharp Avatar asked Apr 06 '26 19:04

zsharp


2 Answers

How many strings will you be concatenating? Do you know for sure how many there will be, or does it depend on how many records are in the database etc?

See my article on this subject for more details and guidelines - but basically, being in a web app makes no difference to how expensive string concatenation is vs using a StringBuilder.

EDIT: I'm afraid it's still not entirely clear from the question exactly what you're doing. If you've got a fixed set of strings to concatenate, and you can do it all in one go, then it's faster and probably more readable to do it using concatenation. For instance:

string faster = first + " " + second + " " + third + "; " + fourth;

string slower = new StringBuilder().Append(first)
                                   .Append(" ")
                                   .Append(second)
                                   .Append(" ")
                                   .Append(third)
                                   .Append("; ")
                                   .Append(fourth)
                                   .ToString();

Another alternative is to use a format string of course. This may well be the slowest, but most readable:

 string readable = string.Format("{0} {1} {2}; {3}",
                                 first, second, third, fourth);

The part of your question mentioning "adding a link each time" suggests using a StringBuilder for that aspect though - anything which naturally leads to a loop is more efficient (for moderate to large numbers) using StringBuilder.

like image 98
Jon Skeet Avatar answered Apr 09 '26 08:04

Jon Skeet


You should take a look at this excellent article by Jon Skeet about concatenating strings.

like image 34
Anteru Avatar answered Apr 09 '26 08:04

Anteru