If strings are immutable in C #, why am I doing this?

I read today, in C # lines are immutable, for example, when they are created, they cannot be changed, therefore how the code works below

string str="a"; str +="b"; str +="c"; str +="d"; str +="e"; console.write(str) //output: abcde 

How the value of a variable has changed

+6
source share
8 answers

Use the reflector to view the ILM code and you will see exactly what is happening. Although your code logically adds new content to the end of the line, behind the scenes the compiler generates ILM code that creates a new line for each assignment.

The image gets a little messier if you combine the literals in one of the following statements:

 str = "a" + "b" + "c" ... 

In this case, the compiler is usually smart enough not to create all the extra lines (and thus work with the garbage collector and translate it for you into ILM code equivalent to:

 str = "abc" 

However, doing this on separate lines like this may not cause this optimization.

+3
source

String objects are immutable, but variables can be reassigned.

You have created individual objects

 a ab abc abcd abcde 

Each of these immutable strings was assigned, in turn, to the str variable.

You cannot change the contents (characters inside) of a string.

Changing a variable is completely different.

+13
source

It is easy to show that the message did not distort the String object as considered:

 string a = "a"; string b = a; Console.WriteLine(object.ReferenceEquals(a, b)); // true Console.WriteLine(a); // a Console.WriteLine(b); // a b += "b"; Console.WriteLine(object.ReferenceEquals(a, b)); // false Console.WriteLine(a); // a Console.WriteLine(b); // ab 

This is because the operator x += y equivalent to x = x + y , but with a smaller character set.

Happy coding.

+5
source

Immutable means that the memory cell used to store the string variable never changes.

 string str ="a"; //stored at some memory location str+= "b"; // now str='ab' and stored at some other memory location str+= "c"; // now str='abc' and stored at some other memory location 

etc.

Whenever you change a value of type string, you never save the new value in its original location, but save it in new memory cells.

 string a="Hello"; string b=a; a="changed"; console.writeline(b); 

Exit

Hello, // variable b , still referring to the original location.

Please check out John Skeet page

http://csharpindepth.com/Articles/General/Strings.aspx

+3
source

Key concepts:

Variable and instance are separate concepts. A variable is what contains a value. In the case of a string, the variable contains a pointer to that string, which is stored somewhere else: an instance.

A variable can always be assigned and reassigned if you want ... it is variable in the end! =)

The instance that I said elsewhere cannot be changed in the case of a string.

By combining strings, just like you, you actually create many different repositories, one for each string concatenation.

The correct way to do this is:

To concatenate a string, you can use the StringBuilder class:

 StringBuilder b = new StringBuilder(); b.Append("abcd"); b.Append(" more text"); string result = b.ToString(); 

You can also use a list of strings and then join it:

 List<string> l = new List<string>(); l.Add("abcd"); l.Add(" more text"); string result = string.Join("", l); 
+2
source

@pst - I agree that readability is important, and in most cases it doesn’t matter on a PC, but what if you are on a mobile platform where system resources are limited?

It is important to understand that StringBuilder is the best way for concatenated strings. It is much faster and more efficient.

You emphasized the important difference, however, as to whether it will be significantly faster and in which scenarios. It is significant that the difference should be measured in ticks at low volumes, since it cannot be measured in milliseconds.

It is important to know that for everyday scenarios on the desktop platform, the difference is imperceptible. But it’s also important to know that for mobile platforms, in extreme cases, when you create large strings or execute thousands of concats or to optimize performance, StringBuilder really wins. With a lot of concat, it's worth noting that StringBuilder takes up a bit more memory.

This is by no means an ideal comparison, but for a fool who combines 1,000,000 lines, StringBuilder outperforms regular string concatenation by ~ 10 minutes (on Core 2 Duo E8500 @ 3.16GHz in Win 7 x64):

 String concat (10): 9 ticks, 0 ms, 8192 bytes String Builder (10): 2 ticks, 0 ms, 8192 bytes String concat (100): 30 ticks, 0 ms, 16384 bytes String Builder (100): 6 ticks, 0 ms, 8192 bytes String concat (1000): 1658 ticks, 0 ms, 1021964 bytes String Builder (1000): 29 ticks, 0 ms, 8192 bytes String concat (10000): 105451 ticks, 34 ms, 2730396 bytes String Builder (10000): 299 ticks, 0 ms, 40624 bytes String concat (100000): 15908144 ticks, 5157 ms, 200020 bytes String Builder (100000): 2776 ticks, 0 ms, 216888 bytes String concat (1000000): 1847164850 ticks, 598804 ms, 1999804 bytes String Builder (1000000): 27339 ticks, 8 ms, 2011576 bytes 

the code:

 class Program { static void Main(string[] args) { TestStringCat(10); TestStringBuilder(10); TestStringCat(100); TestStringBuilder(100); TestStringCat(1000); TestStringBuilder(1000); TestStringCat(10000); TestStringBuilder(10000); TestStringCat(100000); TestStringBuilder(100000); TestStringCat(1000000); TestStringBuilder(1000000); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } static void TestStringCat(int iterations) { GC.Collect(); String s = String.Empty; long memory = GC.GetTotalMemory(true); Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < iterations; i++) { s += "a"; } sw.Stop(); memory = GC.GetTotalMemory(false) - memory; Console.WriteLine("String concat \t({0}):\t\t{1} ticks,\t{2} ms,\t\t{3} bytes", iterations, sw.ElapsedTicks, sw.ElapsedMilliseconds, memory); } static void TestStringBuilder(int iterations) { GC.Collect(); StringBuilder sb = new StringBuilder(); long memory = GC.GetTotalMemory(true); Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < iterations; i++) { sb.Append("a"); } sw.Stop(); memory = GC.GetTotalMemory(false) - memory; Console.WriteLine("String Builder \t({0}):\t\t{1} ticks,\t{2} ms,\t\t{3} bytes", iterations, sw.ElapsedTicks, sw.ElapsedMilliseconds, memory); } } 
+1
source

he didn’t do this; he actually rewrote the variable with a new value, creating each new string object.

0
source

Immutability means that a class cannot be changed. For each + = there you create an entirely new string object.

0
source

Source: https://habr.com/ru/post/894158/


All Articles