gpt4 book ai didi

c# - 编译器会优化 bool 赋值吗?

转载 作者:太空狗 更新时间:2023-10-30 00:08:15 25 4
gpt4 key购买 nike

这就是我想要做的:

if(ABoolean || (BBoolean && CBoolean))
{
SomeButton.Enabled = true;
AnotherButton.Enabled = true;
}
else
{
SomeButton.Enabled = false;
AnotherButton.Enabled = false;
}

我可以将其切换为:

SomeButton.Enabled = (ABoolean || (BBoolean && CBoolean));
AnotherButton.Enabled = (ABoolean || (BBoolean && CBoolean));

更简洁的代码。我的问题是,编译器是否优化了赋值,使其看到 bool 表达式相同并为第二个按钮赋值,还是每次都计算该值。

注意:我知道这是一个微不足道的例子,加速/减速会微不足道,但它会让我更好地理解编译器优化。

编辑:这是我认为第二个选项可能被优化的原因:

class Program
{
static bool ABoolean = true, BBoolean = true, CBoolean = false;
static bool AEnable, BEnable;


static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000000000; i++)
{
Operation1();
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

Stopwatch sw1 = new Stopwatch();
sw1.Start();
for (int i = 0; i < 1000000000; i++)
{
Operation2();
}
sw1.Stop();
Console.WriteLine(sw1.ElapsedMilliseconds);
Console.Read();
}

static void Operation1()
{
if (ABoolean || (BBoolean && CBoolean))
{
AEnable = true;
BEnable = true;
}
else
{
AEnable = false;
BEnable = false;
}
}

static void Operation2()
{
AEnable = (ABoolean || (BBoolean && CBoolean));
BEnable = (ABoolean || (BBoolean && CBoolean));
}
}

这导致在 10 亿次操作中大约有 8-9 秒的差异(第二个选项运行得更快)。然而,当我添加更多“启用” bool 值时,第二个操作变得更慢。

最佳答案

不,我不希望编译器 对其进行优化。 JIT 可能会对此进行优化(因为它有更多信息),但我不希望 C# 编译器这样做。

编译器如何知道 SomeButton.Enabled 是否会有一些副作用,可能会改变 ABooleanBBooleanCBool​​ean?

编辑:对此的验证...让我们给 C# 编译器绝对最的机会:

class Test
{
static void Main()
{
Foo(true, false, true);
}

static void Foo(bool x, bool y, bool z)
{
A = x || (y && z);
B = x || (y && z);
}

static bool A { get; set; }
static bool B { get; set; }
}

编译:

csc /o+ /debug- Test.cs

Foo 通过 ILDASM 的代码:

.method private hidebysig static void  Foo(bool x,
bool y,
bool z) cil managed
{
// Code size 37 (0x25)
.maxstack 8
IL_0000: ldarg.0
IL_0001: brtrue.s IL_000c
IL_0003: ldarg.1
IL_0004: brfalse.s IL_0009
IL_0006: ldarg.2
IL_0007: br.s IL_000d
IL_0009: ldc.i4.0
IL_000a: br.s IL_000d
IL_000c: ldc.i4.1
IL_000d: call void Test::set_A(bool)
IL_0012: ldarg.0
IL_0013: brtrue.s IL_001e
IL_0015: ldarg.1
IL_0016: brfalse.s IL_001b
IL_0018: ldarg.2
IL_0019: br.s IL_001f
IL_001b: ldc.i4.0
IL_001c: br.s IL_001f
IL_001e: ldc.i4.1
IL_001f: call void Test::set_B(bool)
IL_0024: ret
} // end of method Test::Foo

如您所见,表达式实际上在两种情况下都被求值。

关于c# - 编译器会优化 bool 赋值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10852722/

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