gpt4 book ai didi

Java/.NET - 重用值

转载 作者:行者123 更新时间:2023-11-29 04:00:28 25 4
gpt4 key购买 nike

在存储我们经常使用的 String 值时,我们是否减少了内存消耗?

据我所知,每次我们在代码中做一个"some text"声明时,都会构造一个新的String对象,而不是使用一个字符串的地址现有一个具有相同的值(value)。这是正确的吗?

是否可以通过始终寻址相同的 String 而不是创建新的来提高内存效率?

最佳答案

.NET 使用 string intern pool存储字符串。

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.

下面的示例表明,实习生池仅用于文字字符串。 (s2 不引用与 s1 相同的字符串,即使内容相同)

string s1 = "MyTest"; 
string s2 = new StringBuilder().Append("My").Append("Test").ToString();
string s3 = String.Intern(s2);
Console.WriteLine((Object)s2==(Object)s1); // Different references.
Console.WriteLine((Object)s3==(Object)s1); // The same reference.

Java 做 the same thing :

All literal strings and string-valued constant expressions are interned.

关于Java/.NET - 重用值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3924873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com