gpt4 book ai didi

c# - 静态字符串中的属性 Length 是在运行时还是在编译期间计算的?

转载 作者:行者123 更新时间:2023-11-30 20:58:54 25 4
gpt4 key购买 nike

如果我有这段代码

if ("test".Length == 4)

它甚至计算过这个Length 还是编译器计算它并在 IL 代码中使用一个数字?

如果它在运行时完成,则意味着包含此类内容的代码比包含数字的代码要慢。

例如

int length = 2 + 4;

会比

int length = 2 + "test".Length;

这是我想知道的

编辑:根据我自己的基准测试,它似乎运行得同样快,但是我不明白为什么,因为回复告诉我它正在生成 2 个不同的 IL 代码?

那么在不降低性能的情况下在代码中使用它是否安全?

最佳答案

在我的平台上,使用 VS 2010 为 .NET 4 编译的代码,IL DASM 显示

调试

...
IL_0001: ldstr "test"
IL_0006: callvirt instance int32 [mscorlib]System.String::get_Length()
...

发布

...
IL_0000: ldstr "test"
IL_0005: callvirt instance int32 [mscorlib]System.String::get_Length()
...

这意味着没有编译时优化。但是,CLR 抖动可以对此进行优化。通过查看汇编代码可以看到这种优化的结果,这是结果

enter image description here

在我的平台上,在针对 x86 平台的 Release 中编译的代码似乎在进行运行时比较,抖动并未优化代码。

我用的代码

class Program
{
static void Main(string[] args)
{
if ("test".Length == 4) { }
}
}

这是为 if block 生成的汇编代码的一部分。 test 字符串的值在 17 行进行比较。

if ("test".Length == 4)
00000000 push ebp
00000001 mov ebp,esp
00000003 sub esp,8
00000006 mov dword ptr [ebp-4],ecx
00000009 cmp dword ptr ds:[00148ED4h],0
00000010 je 00000017
00000012 call 5D664D0A
00000017 mov ecx,dword ptr ds:[035F2188h]
0000001d cmp dword ptr [ecx],ecx
0000001f call 5D4CA74B
00000024 mov dword ptr [ebp-8],eax
00000027 nop

关于c# - 静态字符串中的属性 Length 是在运行时还是在编译期间计算的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15811224/

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