Jump to content
  • Advertisement
Sign in to follow this  
Thevenin

[.net] String Optimizations in C#

This topic is 3773 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!