Bitterblue
Bitterblue

Reputation: 14095

String vs. StringBuilder when editing a long string?

I have a string that I have to edit quite a lot. Length is undefined. Replace(string, string) will be the most used method for this.

What is better string.Replace("", "") or StringBuilder.Replace("", "") ?

public static string FormatMyString(string input)
{
    // ...
}

(The code examples are plain and stupid. They just serve the purpose to show you what I'm doing. I always get questions: "What are you trying to do ?")

Upvotes: 1

Views: 231

Answers (3)

Enigmativity
Enigmativity

Reputation: 117175

You just don't get any good value just "asking" about these kinds of things. You need to benchmark. Take this code for example:

var sw = Stopwatch.StartNew();
var cc0 = GC.CollectionCount(0);
var s = (string)null;
for (var i = 0; i < 10000000; i++)
{
    s = "a";
    s += "b";
}
var cc1 = GC.CollectionCount(0);
sw.Stop();
Console.WriteLine(
    "collections == {0}, ms == {1}, string == \"{2}\"",
    cc1 - cc0,
    sw.ElapsedMilliseconds,
    s);

Versus this code:

var sw = Stopwatch.StartNew();
var cc0 = GC.CollectionCount(0);
var sb = (StringBuilder)null;
for (var i = 0; i < 10000000; i++)
{
    sb = new StringBuilder();
    sb.Append("a");
    sb.Append("b");
}
var cc1 = GC.CollectionCount(0);
Console.WriteLine(
    "collections == {0}, ms == {1}, string == \"{2}\"",
    cc1 - cc0,
    sw.ElapsedMilliseconds,
    sb.ToString());

The two results I get are:

collections == 63, ms == 336, string == "ab" // +=
collections == 228, ms == 692, string == "ab" // StringBuilder

The StringBuilder takes over twice as long and causes over 3.5 times more garbage collections to occur.

It's certainly the case that if I were to concatenate very long strings that StringBuilder will perform better, but I won't know that point unless I measure it.

You need to provide more detail as to what code you are running and what you mean by "better" (faster, less memory, easy to read code, etc) before we can say what is best.

Upvotes: 0

Shabi_669
Shabi_669

Reputation: 11

IMHO String Builder is the way to go.

It has a cost for creating but would offer much better performence in general due to much more efficient string manipulation and concatenation.

As I said there is a cost so you should consider what does "edit quite a lot" mean.

Sorry I can't provide actual benchmark results right now, but I assume the threshold for using String Builder should be very low...

Hope this helps.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064184

What is better string.Replace("", "") or StringBuilder.Replace("", "") ?

Neither. They both do nothing useful. In the more general case:

  • if you're doing one replacement, the internal-call of String.Replace should be fine
  • if you're doing lots of replacements, consider StringBuilder to avoid intermediate strings

Upvotes: 2

Related Questions