2

I found this piece of code and I'd like to understand why the developer used the string constructor with a char array instead of just a literal constant string:

static string atomLang = new String("lang".ToCharArray());
3
  • 1
    to avoid pooling of the string? Commented Jun 23, 2012 at 18:08
  • Maybe he was trying to make the code more interesting :)). I am sorry about that, but I couldn't resist saying the joke. Commented Jun 23, 2012 at 18:08
  • It's probably because, if you want to initialize it with a string, you can just put static string atomLang = "lang". If you already have a string, why use new? Commented Jun 23, 2012 at 18:12

1 Answer 1

5

The only reason I can think of is to avoid getting a reference to the interned instance of the string.

string str1 = "lang";
string str2 = "lang";
string str3 = new String("lang".ToCharArray());

Console.WriteLine(object.ReferenceEquals(str1, str2));   // Output: true
Console.WriteLine(object.ReferenceEquals(str1, str3));   // Output: false

Not that this will have any practical effects on your code (other than marginal performance differences).

Sign up to request clarification or add additional context in comments.

4 Comments

It should be made clear that this will have a negative effect on performance, if any.
@KonradRudolph: Yes, definitely. Although I suspect there might be rare cases where it might have a positive effect, due to avoiding contention on the same string when shared among multiple cores.
@Douglas, the same string accesses by multiple cores results in shared cache lines which is not harmful. CPUs can share read-only cache lines.
@usr: Yes, the sources I read indicated that memory contention would only occur for writes. Thanks for confirming!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.