gpt4 book ai didi

c# - 'unsafe' 作用域的嵌套会影响性能吗?

转载 作者:行者123 更新时间:2023-12-01 11:11:20 28 4
gpt4 key购买 nike

我想问一下第一个例子是否比第二个例子慢。

例子1:for, unsafe, unsafe, unsafe, etc

for (var i = 0; i < ...; i++)
{
unsafe
{
// ...
}
}

示例 2:不安全,对于

unsafe
{
for (var i = 0; i < ...; i++)
{
// ...
}
}

无处in the documentation这方面正在被涵盖。

问题:

有人可以假设 unsafe 代码块的位置不会影响性能吗?

最佳答案

它们生成完全相同的 IL 代码,因此没有性能差异

嵌套: See on SharpLab

c#

using System;
public class C {
public void M() {
var x = 0;
for (var i = 0; i < 100; i++)
{
unsafe { x+=i; }
}
}
}

IL

.class private auto ansi '<Module>'
{
} // end of class <Module>

.class public auto ansi beforefieldinit C
extends [System.Private.CoreLib]System.Object
{
// Methods
.method public hidebysig
instance void M () cil managed
{
// Method begins at RVA 0x2050
// Code size 20 (0x14)
.maxstack 2
.locals init (
[0] int32,
[1] int32
)

IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
// sequence point: hidden
IL_0004: br.s IL_000e
// loop start (head: IL_000e)
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: add
IL_0009: stloc.0
IL_000a: ldloc.1
IL_000b: ldc.i4.1
IL_000c: add
IL_000d: stloc.1

IL_000e: ldloc.1
IL_000f: ldc.i4.s 100
IL_0011: blt.s IL_0006
// end loop

IL_0013: ret
} // end of method C::M

.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x2070
// Code size 7 (0x7)
.maxstack 8

IL_0000: ldarg.0
IL_0001: call instance void [System.Private.CoreLib]System.Object::.ctor()
IL_0006: ret
} // end of method C::.ctor

} // end of class C

周边: See on SharpLab

c#

using System;
public class C {
public void M() {
var x = 0;
unsafe {
for (var i = 0; i < 100; i++)
{
x+=i;
}
}
}
}

IL

.class private auto ansi '<Module>'
{
} // end of class <Module>

.class public auto ansi beforefieldinit C
extends [System.Private.CoreLib]System.Object
{
// Methods
.method public hidebysig
instance void M () cil managed
{
// Method begins at RVA 0x2050
// Code size 20 (0x14)
.maxstack 2
.locals init (
[0] int32,
[1] int32
)

IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
// sequence point: hidden
IL_0004: br.s IL_000e
// loop start (head: IL_000e)
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: add
IL_0009: stloc.0
IL_000a: ldloc.1
IL_000b: ldc.i4.1
IL_000c: add
IL_000d: stloc.1

IL_000e: ldloc.1
IL_000f: ldc.i4.s 100
IL_0011: blt.s IL_0006
// end loop

IL_0013: ret
} // end of method C::M

.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x2070
// Code size 7 (0x7)
.maxstack 8

IL_0000: ldarg.0
IL_0001: call instance void [System.Private.CoreLib]System.Object::.ctor()
IL_0006: ret
} // end of method C::.ctor

} // end of class C

关于c# - 'unsafe' 作用域的嵌套会影响性能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60018929/

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