字符串不变性 [英] String Immutability

查看:134
本文介绍了字符串不变性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由语句是否字符串不变性的工作,或在一份声明中字符串?

例如,据我所知,下面的code将拨出两个字符串在堆上。

 字符串s =你好;
S + =的世界!;
 

你好将留在堆中,直到垃圾回收;现在S变量世界,你好!在堆上。然而,有多少串并以下行分配堆... 1或2?此外,有没有一个工具/方法来验证结果?

 字符串s =再见+残酷的世界!
 

解决方案

编译器有对字符串连接,这是特殊待遇,为什么第二个例子是只有永远的一个字符串。而实习是指,即使你跑这条线20000次仍然只有1串。

重新测试结果...的最简单的方式(在这种情况下)可能是看在反射器:

 。方法私人hidebysig静态无效的主要()CIL管理
{
    。入口点
    .maxstack 1
    .locals的init(
        [0]字符串s)
    L_0000:ldstr再见残酷的世界!
    L_0005:stloc.0
    L_0006:ldloc.0
    L_0007:拨打无效[mscorlib程序] System.Console:的WriteLine(字符串)
    L_000c:RET
}
 

正如你所看到的( ldstr ),编译器做了这个给你了。

Does string immutability work by statement, or by strings within a statement?

For example, I understand that the following code will allocate two strings on the heap.

string s = "hello ";
s += "world!";

"hello" will remain on the heap until garbage collected; and s now references "hello world!" on the heap. However, how many strings does the following line allocate on the heap...1 or 2? Also, is there a tool/way to verify the results?

string s = "goodbye " + "cruel world!";

解决方案

The compiler has special treatment for string concatenation, which is why the second example is only ever one string. And "interning" means that even if you run this line 20000 times there is still only 1 string.

Re testing the results... the easiest way (in this case) is probably to look in reflector:

.method private hidebysig static void Main() cil managed
{
    .entrypoint
    .maxstack 1
    .locals init (
        [0] string s)
    L_0000: ldstr "goodbye cruel world!"
    L_0005: stloc.0 
    L_0006: ldloc.0 
    L_0007: call void [mscorlib]System.Console::WriteLine(string)
    L_000c: ret 
}

As you can see (ldstr), the compiler has done this for you already.

这篇关于字符串不变性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆