gpt4 book ai didi

C# vs C++ 三元运算符

转载 作者:IT老高 更新时间:2023-10-28 22:59:27 29 4
gpt4 key购买 nike

我曾经是 Windows 上的 C++ 程序员。我知道编译器会优化 C++ 中的三元运算符。

C++ 代码:

#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
int result = argc > 3 ? 1 : 5;
printf("%d", result);
return 0;
}

由于管道的关系,生成的原生代码如下图(当然是Release模型):

int result = argc > 3 ? 1 : 5;
00B21003 xor eax,eax
00B21005 cmp dword ptr [argc],3
00B21009 setle al
00B2100C lea eax,[eax*4+1]

C#代码:

namespace TernaryOperatorCSharp
{
static void Main(string[] args)
{
int argc = args.Length;
int result = argc > 1 ? 2 : 5;
System.Console.WriteLine(result);
}
}

我查了JIT生成的native code,但是根本没有优化(还是两条跳转指令)。

int result = argc > 1 ? 2 : 5;
0000002f cmp dword ptr [ebp-4],1
00000033 jg 0000003F
00000035 nop
00000036 mov dword ptr [ebp-0Ch],5
0000003d jmp 00000046
0000003f mov dword ptr [ebp-0Ch],2
00000046 mov eax,dword ptr [ebp-0Ch]
00000049 mov dword ptr [ebp-8],eax
System.Console.WriteLine(result);
0000004c mov ecx,dword ptr [ebp-8]
0000004f call 6A423CBC

为什么 C# JIT 编译器不进行与 C++ 编译器相同的优化?

这背后的故事是什么?

任何信息将不胜感激。


你好,我已经修改了 C# 程序并使用发布模型运行它。

之前

int result = args.Length > 1 ? 2 : 5;

现在

int argc = args.Length;
int result = argc > 1 ? 2 : 5;

但结果还是一样。还有两条跳转指令存在。如果有更多信息,我将不胜感激。

最佳答案

您没有使用优化进行编译 - nop 指令表明了这一点(编译器插入这些以用作 anchor ,以便您可以在大括号上放置断点)。

即使您选中了“优化代码”复选框,Visual Studio 也不会始终生成优化代码。通常,当您在调试器中启动时,无论如何它都会禁用优化,以便调试 session 的行为更加符合您的预期。

此外,您不是在将苹果与苹果进行比较,这占了更多的麻烦。

string[].Length 是 C# 中的属性,不是公共(public)变量,更不是局部变量。通过使用代码,属性通常被视为公共(public)变量,但实际上可以作为成熟的 get/set 方法存在。编译器必须发出代码来处理这个问题,尤其是当 Property 在单独的程序集中定义时。

尝试使用本地 int 变量并打开编译器优化的示例(使用优化构建,启动程序,启动后附加调试器,查看反汇编)。

关于C# vs C++ 三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20827111/

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