Java字面量 存储位置_Java和.NET字符串文字存放在哪里?

.NET中的字符串是引用类型,因此它们始终在堆上(即使在插入时也是如此)。您可以使用调试器(例如WinDbg)进行验证。

如果您有以下课程

class SomeType {

public void Foo() {

string s = "hello world";

Console.WriteLine(s);

Console.WriteLine("press enter");

Console.ReadLine();

}

}

然后调用Foo()实例,可以使用WinDbg来检查堆。

该引用很可能存储在一个小程序的寄存器中,因此最简单的方法是通过执行来查找对特定字符串的引用!dso。这为我们提供了有关字符串的地址:

0:000> !dso

OS Thread Id: 0x1660 (0)

ESP/REG  Object   Name

002bf0a4 025d4bf8 Microsoft.Win32.SafeHandles.SafeFileHandle

002bf0b4 025d4bf8 Microsoft.Win32.SafeHandles.SafeFileHandle

002bf0e8 025d4e5c System.Byte[]

002bf0ec 025d4c0c System.IO.__ConsoleStream

002bf110 025d4c3c System.IO.StreamReader

002bf114 025d4c3c System.IO.StreamReader

002bf12c 025d5180 System.IO.TextReader+SyncTextReader

002bf130 025d4c3c System.IO.StreamReader

002bf140 025d5180 System.IO.TextReader+SyncTextReader

002bf14c 025d5180 System.IO.TextReader+SyncTextReader

002bf15c 025d2d04 System.String    hello world             // THIS IS THE ONE

002bf224 025d2ccc System.Object[]    (System.String[])

002bf3d0 025d2ccc System.Object[]    (System.String[])

002bf3f8 025d2ccc System.Object[]    (System.String[])

现在使用!gcgen找出实例在哪个世代:

0:000> !gcgen 025d2d04

Gen 0

它是零代-即它刚刚被分配。谁在生根?

0:000> !gcroot 025d2d04

Note: Roots found on stacks may be false positives. Run "!help gcroot" for

more info.

Scan Thread 0 OSTHread 1660

ESP:2bf15c:Root:025d2d04(System.String)

Scan Thread 2 OSTHread 16b4

DOMAIN(000E4840):HANDLE(Pinned):6513f4:Root:035d2020(System.Object[])->

025d2d04(System.String)

ESP是我们Foo()方法的堆栈,但请注意,我们也有一个object[]。那就是实习表。让我们来看看。

0:000> !dumparray 035d2020

Name: System.Object[]

MethodTable: 006984c4

EEClass: 00698444

Size: 528(0x210) bytes

Array: Rank 1, Number of elements 128, Type CLASS

Element Methodtable: 00696d3c

[0] 025d1360

[1] 025d137c

[2] 025d139c

[3] 025d13b0

[4] 025d13d0

[5] 025d1400

[6] 025d1424

...

[36] 025d2d04  // THIS IS OUR STRING

...

[126] null

[127] null

我稍微减少了输出,但是您明白了。

总结:字符串在堆上-即使在插入时也是如此。实习表保留对堆上实例的引用。也就是说,在GC期间不收集实习生字符串,因为实习生表将它们作为根。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值