trên thực tế cả hai vòng lặp sẽ có một cơ thể trống rỗng khi biên soạn!
để làm cho vòng lặp cư xử thứ hai, bạn sẽ phải loại bỏ các (object)
đúc
đây là những gì nó trông giống như khi tôi biên dịch mã của bạn,
public struct MyStruct
{
}
class Program
{
static void Main(string[] args)
{
test1();
test2();
}
public static void test1()
{
Stopwatch sw = new Stopwatch();
bool b;
MyStruct s;
for (int i = 0; i < 100000000; i++)
{
b = (object)s == null;
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Console.ReadLine();
}
public static void test2()
{
Stopwatch sw = new Stopwatch();
bool b;
MyStruct? s = null;
for (int i = 0; i < 100000000; i++)
{
b = (object)s == null;
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Console.ReadLine();
}
}
IL:
các MyStruct (trống vì bạn không cung cấp bất kỳ)
.class public sequential ansi sealed beforefieldinit ConsoleApplication1.MyStruct
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
} // end of class ConsoleApplication1.MyStruct
firs t vòng lặp trong ví dụ của bạn
.method public hidebysig static
void test1() cil managed
{
// Method begins at RVA 0x2054
// Code size 17 (0x11)
.maxstack 2
.locals init (
[0] valuetype ConsoleApplication1.MyStruct s,
[1] int32 i
)
IL_0000: ldc.i4.0
IL_0001: stloc.1
IL_0002: br.s IL_0008
// loop start (head: IL_0008)
IL_0004: ldloc.1
IL_0005: ldc.i4.1
IL_0006: add
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4 100000000
IL_000e: blt.s IL_0004
// end loop
IL_0010: ret
} // end of method Program::test1
vòng lặp thứ hai
.method public hidebysig static
void test2() cil managed
{
// Method begins at RVA 0x2074
// Code size 25 (0x19)
.maxstack 2
.locals init (
[0] valuetype [mscorlib]System.Nullable`1<valuetype ConsoleApplication1.MyStruct> s,
[1] int32 i
)
IL_0000: ldloca.s s
IL_0002: initobj valuetype [mscorlib]System.Nullable`1<valuetype ConsoleApplication1.MyStruct>
IL_0008: ldc.i4.0
IL_0009: stloc.1
IL_000a: br.s IL_0010
// loop start (head: IL_0010)
IL_000c: ldloc.1
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4 100000000
IL_0016: blt.s IL_000c
// end loop
IL_0018: ret
} // end of method Program::test2
mã này sẽ không biên dịch; Lỗi 1 Sử dụng biến địa phương chưa được gán 'cho vòng lặp thứ hai – Fredou
@Fredou Đúng vậy. Một lỗi đánh máy trong thực tế. Tôi sẽ cập nhật câu trả lời của tôi với một số điểm chuẩn - Tôi đã tìm thấy lỗi trong mã thời gian – nawfal
mã này, khi được biên dịch, dường như đang chạy vòng lặp trống, bạn nên đăng mã điểm chuẩn thực tế của mình vì tôi không thấy cách bạn có thể nhận 7500ms – Fredou