Memory allocation with strings

本文通过两个案例探讨了C#中字符串变量的内存管理机制。解释了.NET运行时如何通过内部池来确保相同字面量字符串常量仅存在单一实例,并分析了使用new关键字创建字符串时的不同行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

string s1, s2;

case #1:
s1 = "Tom";
s2 = "Tom";
MessageBox.Show(string.Format("Is s2 the same reference as s1?: {0}", (Object)s2==(Object)s1));

case #2:
s1 = new string('t', 2);
s2 = new string('t', 2);
MessageBox.Show(string.Format("Is s2 the same reference as s1?: {0}", (Object)s2==(Object)s1));

For case#1, we will see the s2 is the same reference as s1.
For case#2, we will find the s2 is not the same reference as s1.

Explain:
MSDN topic for string.IsIntern() method:
The common language runtime automatically maintains a table, called the "intern pool", which contains a single instance of each unique literal string constant declared in a program, as well as any unique instance of String you add programmatically.
The intern pool conserves string storage. If you assign a literal string constant to several variables, each variable is set to reference the same constant in the intern pool instead of referencing several different instances of String that have identical values.

MSDN topic for string.Intern() method:
The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.
For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable.
The Intern method uses the intern pool to search for a string equal to the value of str. If such a string exists, its reference in the intern pool is returned. If the string does not exist, a reference to str is added to the intern pool, then that reference is returned.

Summary:
The common languange runtime maintains the intern pool table for string constants only, not suitable for new constructed string by "new string()" or "new StringBuilder()", so if two string variables were assigned to same constant, then they refer to the same object in memory, otherwise they refer to which there are two different objects with same string value in memory.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值