Does String.Replace always recreate a new string object?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sin Jeong-hun

    Does String.Replace always recreate a new string object?

    If I use something like this,

    string html = "<h1>C# is great</h1>";
    Console.WriteLi ne(html.Replace ("&lt;","<").Re place("&gt;","> "));

    Does this recreate new string objects two times, even though it has
    nothing to replace, and it is OK to return the same string object?

    I know, regular expression is a more delicate way to do this, but it
    always is kind of too complicated to me.
    Thank you.
  • Hilton

    #2
    Re: Does String.Replace always recreate a new string object?


    "Sin Jeong-hun" <typingcat@gmai l.comwrote in message
    news:656870e0-4f9a-4ace-867a-b1a12520cb25@j2 8g2000hsj.googl egroups.com...
    If I use something like this,
    >
    string html = "<h1>C# is great</h1>";
    Console.WriteLi ne(html.Replace ("&lt;","<").Re place("&gt;","> "));
    >
    Does this recreate new string objects two times, even though it has
    nothing to replace, and it is OK to return the same string object?
    No, Replace (string, string) does not always create a new string.

    Hilton


    Comment

    • Marc Gravell

      #3
      Re: Does String.Replace always recreate a new string object?

      This returns true because the CLR uses string interning to optimize
      string handling.
      Actually it seems to work even if the strings aren't interned, suggesting it
      is instead a "I didn't update anything, return the original reference"
      optimisation; since it is an internal-call, it is hard to check...

      Anyways, s1 and s2 come out as ref-equals, even though it isn't interned.

      Marc

      string s0 = "foobar"; // expect this to be interned
      Console.WriteLi ne("s0: {0}", s0);
      Console.WriteLi ne("s0 interned: {0}", (string.IsInter ned(s0) !=
      null));
      string s1 = new string('a',5); // don't expect this to be
      interned
      Console.WriteLi ne("s1: {0}", s1);
      Console.WriteLi ne("s1 interned: {0}", (string.IsInter ned(s1) !=
      null));
      string s2 = s1.Replace("b", "c");
      Console.WriteLi ne("s2: {0}", s1);
      Console.WriteLi ne("ref-equals: {0}", object.Referenc eEquals(s1,
      s2));
      Console.WriteLi ne("s1 interned: {0}", (string.IsInter ned(s1) !=
      null));
      Console.WriteLi ne("s2 interned: {0}", (string.IsInter ned(s2) !=
      null));


      Comment

      • Marc Gravell

        #4
        Re: Does String.Replace always recreate a new string object?

        (I'm going to have to find a faster nntp feed ;-p)


        Comment

        Working...