gpt4 book ai didi

c# - 下面的代码创建了多少个字符串对象?

转载 作者:太空狗 更新时间:2023-10-29 21:32:31 26 4
gpt4 key购买 nike

string s = "";
for(int i=0;i<10;i++) {
s = s + i;
}

我一直在用这些选项来回答这个问题。

  1. 1
  2. 11
  3. 10
  4. 2

我有这段简单的代码,我只想知道这段代码会创建多少个字符串对象。

我有疑问,是不是 string s = ""; 没有创建任何对象。我不这么认为,请告诉我。

如果我用 + 运算符附加字符串,它会创建新字符串,所以我认为这将是在 for 循环的每次迭代中创建的新对象。

所以我认为将创建 11 个对象。如果我不正确,请告诉我。

String result = "1" + "2" + "3" + "4";  //Compiler will optimise this code to the below line.
String result = "1234"; //So in this case only 1 object will be created??

我点击了下面的链接,但仍然不清楚。

Link1

请同时涵盖 string strstring str = null 的情况。如果我们不初始化字符串以及当我将字符串分配给 null 时会发生什么。所以在这两种情况下它将是一个对象或没有对象。

string str;

string str = null;

在代码的后面,如果我这样做的话。

str = "abc";

是否有任何编程方法来计算对象的数量?,因为我认为这可能是一个有争议的话题。我怎样才能通过一些编程或一些工具达到 100%?我在 IL 代码中看不到这一点。

我试过下面的代码,只是为了确定是否创建了新对象。它为每次迭代写入“不同”。这意味着它总是给我一个不同的对象,所以可能有 10 个或 20 个对象。因为它没有给我中间状态的信息(在执行 s = s + i 时为 i 装箱)

    string s = "0";
object obj = s;
for (int i = 0; i < 10; i++)
{
s = s + i;

if (Object.ReferenceEquals(s, obj))
{
Console.Write("Same");
}
else
{
Console.Write("Different");
}
}

我不同意 string str = "" 不创建任何对象的说法。我实际尝试过这个。

    string s = null;
object obj = null;

if (Object.ReferenceEquals(s, obj))
{
Console.Write("Same");
}
else
{
Console.Write("Different");
}

代码写“Same”,但如果我写 string s = "";,它会在控制台上写“Different”。

我现在又多了一个疑问。

s = s + is = s + i.ToString() 有什么区别。

s = s + i.ToString() 接口(interface)代码

IL_000f:  call       instance string [mscorlib]System.Int32::ToString()
IL_0014: call string [mscorlib]System.String::Concat(string, string)

s = s + i 语言代码

IL_000e:  box        [mscorlib]System.Int32
IL_0013: call string [mscorlib]System.String::Concat(object, object)

那么盒子和实例之间有什么区别

最佳答案

好吧,让我们数数:

string s = ""; // no new objects created, s assigned to string.Empty from the cache

// 10 times:
for(int i = 0; i < 10; i++) {
// i <- first object to create (boxing): (object) i
// s + i <- second object to create: string.Concat(s, (object) i);
s = s + i;
}

要测试 string s = "" 不会创建您可以放置​​的额外对象

string s = "";

if (object.ReferenceEquals(s, string.Empty))
Console.Write("Empty string has been cached");

最后,我们有 20 个对象:0 + 10 * 2(10 盒装 int10 string)。万一

string result = "1" + "2" + "3" + "4";

如您所见,结果 可以并且(将)在编译时 计算,因此只有一个对象 ("1234") 将被创建。万一

string str; // just a declaration, str contains trash

string str = null; // no objects created
...
str = "abc"; // an object ("abc") created

关于c# - 下面的代码创建了多少个字符串对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40524468/

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