Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An example Analysis of string Optimization of C #

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the "string optimization example analysis of C#". In the daily operation, I believe that many people have doubts about the string optimization example analysis of C#. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "string optimization example analysis of C#"! Next, please follow the editor to study!

First, let's take a look at a program:

Using System; class Program {static void Main (string [] args) {string a = "hello world"; string b = a; a = "hello"; Console.WriteLine ("{0}, {1}", a, b); Console.WriteLine (a = = b); Console.WriteLine (object.ReferenceEquals (a, b));}}

There is nothing special about this. I believe everyone knows the result of the operation:

Hello, hello worldFalseFalse

The second WriteLine uses = = to compare two strings and returns False because they are inconsistent. The last WriteLine returns False because the references to an and b are inconsistent.

Next, we add code at the end of the code:

Console.WriteLine ((a + "world") = = b); Console.WriteLine (object.ReferenceEquals ((a + "world"), b))

I believe that the output of this will not be unexpected. The former returns True because the contents on both sides of = = are equal; the latter is False because a new string instance is created after the + operator is executed, which is inconsistent with the reference to b.

These are the usual ways objects work. Two separate objects can have the same content, but they are different individuals.

Next, let's talk about what's unusual about string.

Take a look at the following code:

Using System;class Program {static void Main (string [] args) {string hello = "hello"; string helloWorld = "hello world"; string helloWorld2 = hello + "world"; Console.WriteLine ("{0}, {1}: {2}, {3}", helloWorld, helloWorld2, helloWorld = = helloWorld2, object.ReferenceEquals (helloWorld, helloWorld2));}}

Run it, and the result is:

Hello world, hello world: True, False

Again, no surprise, = = returns true because they have the same content, and ReferenceEquals returns False because they are different references.

Now add code like this later:

HelloWorld2 = "hello world"; Console.WriteLine ("{0}, {1}: {2}, {3}", helloWorld, helloWorld2, helloWorld = = helloWorld2, object.ReferenceEquals (helloWorld, helloWorld2))

Run, the result is:

Hello world, hello world: True, True

Wait a minute, the hellowWorld here is consistent with the helloWorld2 reference? I believe many people cannot accept this result. The helloWorld2 here should be the same as the hello + "world" above, but why does ReferenceEquals return True?

String.Intern

Experienced programmers should know that the number of strings in a large project is huge. Sometimes hundreds, thousands, or even tens of thousands of duplicate strings exist. The contents of these strings are the same, but they will repeatedly allocate memory and take up a huge amount of storage space, which must be optimized. When dealing with this problem, C# adopts the common practice of establishing an internal pool, and each different string in the pool has a unique individual in the pool (this scheme can be seen in all kinds of large projects). After all, C# is a language, not a specific domain-oriented technology, so it cannot make this internal pooling technology fully automated. Because we don't know what scale C# will be used in projects in the future. If fully automated maintenance of this internal pool may result in a huge waste of memory in large projects, after all, not all strings need to be added to this resident pool. Therefore, C # provides String.Intern and String.IsInterned interfaces, leaving it to the programmer to maintain the internal pool.

How String.Intern works is easy to understand. You use this interface with a string as a parameter, and return a reference to this existence if the string already exists in the pool; if it does not exist, add it to the pool and return a reference, for example:

Console.WriteLine (object.ReferenceEquals (String.Intern (helloWorld), String.Intern (helloWorld2)

This code will return True, and although the references to helloWorld and helloWorld2 are different, their contents are the same.

Here we take a few minutes to test String.Intern, because in some cases, it produces results that are a bit counterintuitive. Here is an example:

String a = new string (new char [] {'a', 'baked,' c'}); object o = String.Copy (a); Console.WriteLine (object.ReferenceEquals (o, a)); String.Intern (o.ToString ()); Console.WriteLine (object.ReferenceEquals (o, String.Intern (a)

It's understandable that the first WriteLine returns False, because String.Copy creates a new instance of a, so references to o and an are not used.

But why does the second WriteLine return True? Think about it. Here's another example:

Object O2 = String.Copy (a); String.Intern (o2.ToString ()); Console.WriteLine (object.ReferenceEquals (O2, String.Intern (a)

This seems to do the same thing as the one above, but why does WriteLine return False?

First, you need to explain how ToString works, which always returns its own reference. O is a variable pointing to "abc", and this is the reference returned by calling ToString. So, for the above content, it can be explained as follows:

At first, the variable a points to the string object "abc" (# 1), and the variable o points to another string object (# 2), which also contains "abc".

Call String.Intern (o.ToString ()) to add a reference to object # 2 to the internal pool.

Now that the # 2 object is already in the pool, any time you call String.Intern with "abc", you will return a reference to # 2 (o points to this object).

So, when you use ReferenceEquals to compare o with String.Intern (a), return True. Because String.Intern (a) returns a reference to # 2.

Now let's create a new variable O2 and use String.Copy (a) to create a new object # 3, which also contains "abc".

The call to String.Intern (o2.ToString ()) adds nothing to the internal pool because "abc" already exists (# 2).

So, calling Intern at this point returns a reference to object # 2. Note that code like O2 = String.Intern (o2.ToString ()) is not used here.

This is why the last line of WriteLine prints the False, because we are trying to compare # 3 and # 2 references. If you add a code such as O2 = String.Intern (o2.ToString ()) as mentioned in 7, WriteLine returns True.

String.IsInterned

IsInterned, as its name is, determines whether a string is already in the internal pool. If the string passed in is already in the pool, a reference to the string object is returned, and null is returned if it is no longer in the pool.

Here is an example of IsInterned:

String s = new string (new char [] {'x','y','z'}); Console.WriteLine (String.IsInterned (s)? "not interned"); String.Intern (s); Console.WriteLine (String.IsInterned (s)? "not interned"); Console.WriteLine (object.ReferenceEquals (String.IsInterned (new string (new char [] {'x,'y','z'})), s)

The first WriteLine prints "not interned" because "xyz" does not yet exist in the internal pool; the second WriteLine prints "xyz" because there is now "xyz" in the internal pool; and the third WriteLine prints True because the object refers to the "xyz" in the internal pool.

Constant strings are automatically added to the internal pool

Change the last line of code to:

Console.WriteLine (object.ReferenceEquals ("xyz", s))

You'll find that something strange happens. The code no longer outputs "not interned", and the last two WriteLine outputs False! What happened?

The reason is the constant "xyz" in the last line of code, and CLR automatically adds the character constants used in the program to the internal pool. So, when the last line is added, "xyz" already exists in the internal pool before the program "runs" (avoid rigor, use quotation marks here). So, when you call String.IsInterned, you no longer return null, but a reference to "xyz". This also explains why the later ReferenceEquals returns False, because s has never been added to the internal pool, and it does not point to the "xyz" of the internal pool.

The compiler is smarter than you think.

Change the last line of code to:

Console.WriteLine (object.ReferenceEquals ("x" + "y" + "z", s))

Run it and you will find that the result is the same as using "xyz" directly. But the + operator is used here? The compiler should not know the final result of "x" + "y" + "z"?

In fact, if you replace "x" + "y" + "z" with String.Format ("{0} {1} {2}", "x", "x", "y", "z"), the result will be different. For some reason, CLR treats strings linked with the + operator as constants, while String.Format needs to know the result at run time. Why? Take a look at the following code:

Using System; class Program {public static void Main () {Console.WriteLine ("x" + "y" + "z");}}

After this code has been compiled and viewed using Ildasm.exe, you will see:

Screenshot-ILDasm intern-xyz Main method.png

See, the compiler is smart enough to replace "x" + "y" + "z" with "xyz".

At this point, the study of "string optimization example analysis of C#" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report