- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我读了 Jon Skeet 的测验,我想知道为什么我的第二个样本不起作用而第一个样本起作用。
为什么这会产生 true
:
object x = new string("".ToArray());
object y = new string("".ToArray());
Console.WriteLine(x == y); //true
但这个不是:
var k="k";
//string.intern(k); // doesn't help
object x = new string(k.ToArray());
object y = new string(k.ToArray());
Console.WriteLine(x == y); //false
我在 vs2010 上使用 fw 4.5。
幸运的是我也安装了 vs2005,同样的结果:
最佳答案
这是 Eric Lippert 的一篇博文,它回答了您的问题:String interning and String.Empty .
他描述了类似的情况:
object obj = "Int32";
string str1 = "Int32";
string str2 = typeof(int).Name;
Console.WriteLine(obj == str1); // true
Console.WriteLine(str1 == str2); // true
Console.WriteLine(obj == str2); // false !?
所以想法是,实习并不意味着您只有一个特定 string
的实例,即使它是实习的。 默认情况下仅驻留编译时文字。这意味着以下代码打印为真:
var k1 = "k";
object k2 = "k";
Console.WriteLine(k1 == k2);
但是,如果您尝试在运行时以编程方式创建包含 "k"
内容的字符串,例如使用 string(char[])
构造函数,在对象上调用 ToString()
,使用 StringBuilder
等,您不会得到 interned string默认。这个打印错误;
var k1 = "k";
object k2 = new string("k".ToCharArray());
Console.WriteLine(k1 == k2);
为什么?因为在运行时驻留字符串是昂贵的。
There Ain't No Such Thing As A Free Lunch.
(...)
In short, it is in the general case not worth it to intern all strings.
关于空字符串的不同行为:
Some versions of the .NET runtime automatically intern the empty string at runtime, some do not!
关于c# - 空字符串作为特例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22138144/
数组的倒置计数表示——数组离排序有多远(或接近)。如果数组已经排序,则反转计数为 0。如果数组以相反的顺序排序,则反转计数为最大值。形式上来说,如果 a[i] > a[j] 且 i < j,则两个元素
假设我有两座建筑物,我可以在其中 build 不同的单元。一个建筑物只能同时 build 一个单元,但有一个最多 5 个单元的 fifo 队列,它们将按顺序 build 。每个单元都有构建时间。我需要
我正在执行一个查询并从数组中的数据库中获取以下数据(MySql2 类型对象): +-----------+---------------+---------------+------+------+
在 ghci 中: λ> :t (pure 1) (pure 1) :: (Applicative f, Num a) => f a λ> show (pure 1) :1:1: No ins
在这种特殊情况下,我不会让 file_get_contents() 返回页面,其中 url 包含一个“Ö”字符。 $url = "https://se.timeedit.net/web/liu/db1
这是我的字符串10000000000000000000000000000000000000000000000000000000000 与 60 1/0 组合的字符串。 我想把它放入一个 int Arr
你好, 我有以下代码: 43 while (TRUE) 44 { 45 printf("Swipe Card: "); 46 scanf("%s
我正在寻找在多项式时间内解决的 3-SAT 特例及其算法。任何链接? 谢谢。 最佳答案 阅读 Thomas J Schaeffer 的优秀(但有点难以阅读)论文:The Complexity of S
我正在清理我的一个旧项目。它必须做的一件事是——给定笛卡尔网格系统和网格上的两个正方形,找到所有正方形的列表,连接这两个正方形中心的线将通过这些正方形。 这里的特殊情况是所有起点和终点都被限制在正方形
如果你在“alloc.c”中有如下代码: typedef __typeof__(sizeof(int)) size_t; extern void *calloc (size_t __nmemb, si
我在 Ruby 中有一个数组,其值如下 xs = %w(2.0.0.1 2.0.0.6 2.0.1.10 2.0.1.5 2.0.0.8) 等等。我想对数组进行排序,使最终结果应该是这样的: ys =
关于将应用程序提交到 iOS AppStore,我遇到了一个非常独特的困境。 这是一款适用于 1.5 至 3 岁 child 的应用程序,该应用程序背后的想法是通过语音引导您学习动物名称和它们的声音。
我是一名优秀的程序员,十分优秀!