Sign in to follow this  

[.net] String Optimizations in C#

This topic is 3485 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm working on a List control, and I'm wondering if I can use the string reference as a unique identifier for its position in the list. In Java, you can write..
String x = "abc";
String y = "abc";
...and both x and y may get optimized to have the same memory location. Thus, the reference cannot be used as a unique identifier. Does C# do this also?

Share this post


Link to post
Share on other sites
Damnit.

Quote:
Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator (Section 7.9.7) appear in the same assembly, these string literals refer to the same string instance. For instance, the output produced by
Copy Code

class Test
{
static void Main() {
object a = "hello";
object b = "hello";
System.Console.WriteLine(a == b);
}
}

is True because the two literals refer to the same string instance.

- http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx


Looks like I'll have to write something like..

class cSafeString
{
public string MyString;
}

Share this post


Link to post
Share on other sites
in C# you can use the == to test two string for equality because it has operator overloading so in C# "a == b" is the same as "a.equals(b)" in java.

Quote:

Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references (7.9.7 String equality operators). This makes testing for string equality more intuitive.

Share this post


Link to post
Share on other sites
Object.ReferenceEquals()
will test to see if the references (not the values) of the two strings are equal, but be warned, the compiler optimizes identical literals to be the same instance.


string a = "test";
string b = "test";

Object.ReferenceEquals(a, b); // returns true due to compiler.

a = Console.ReadLine(); // If it type in "test"
b = Console.ReadLine(); // and "test" again...

Object.ReferenceEquals(a, b); // returns false this time.

Share this post


Link to post
Share on other sites

This topic is 3485 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this