【发布时间】:2013-08-25 18:31:04
【问题描述】:
考虑这段代码:
namespace FastReflectionTests
{
public class Test
{
public void Method1()
{
var x = 10;
var y = 20;
if (x == 10 && y == 20)
{
}
}
public void Method2()
{
var x = 10;
var y = 20;
if (x == 10 && y == 20)
{
}
}
}
}
现在考虑 IL 代码:
这是方法1:
instance void Method1 () cil managed
{
// Method begins at RVA 0x3bd0
// Code size 17 (0x11)
.maxstack 2
.locals init (
[0] int32 x,
[1] int32 y
)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldc.i4.s 20
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldc.i4.s 10
IL_0009: bne.un.s IL_0010
IL_000b: ldloc.1
IL_000c: ldc.i4.s 20
IL_000e: pop
IL_000f: pop
IL_0010: ret
} // end of method Test::Method1
这是方法2:
instance void Method2 () cil managed
{
// Method begins at RVA 0x3bf0
// Code size 17 (0x11)
.maxstack 2
.locals init (
[0] int32 x,
[1] int32 y
)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldc.i4.s 20
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldc.i4.s 10
IL_0009: bne.un.s IL_0010
IL_000b: ldloc.1
IL_000c: ldc.i4.s 20
IL_000e: pop
IL_000f: pop
IL_0010: ret
} // end of method Test::Method2
method1 得到 00:00:00.0000019 秒的调用时间。
method2 得到 00:00:00.0000006 秒的调用时间。
我写这段代码是为了测试
public class Program
{
private static void Main(string[] args)
{
var test = new Test();
test.Method1();
test.Method2();
System.Console.ReadLine();
}
}
public class Test
{
public void Method1()
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var x = 10;
var y = 20;
if (x == 10)
{
if (y == 20)
{
}
}
stopwatch.Stop();
Console.WriteLine("Time Method1: {0}",
stopwatch.Elapsed);
}
public void Method2()
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var x = 10;
var y = 20;
if (x == 10 && y == 20)
{
}
stopwatch.Stop();
Console.WriteLine("Time Method2: {0}",
stopwatch.Elapsed);
}
}
我改变了method1和method2的位置。
test.Method2();
test.Method1();
然后重新运行测试。
method1 获得 00:00:00.0000006 秒的调用时间。
method2 获取 00:00:00.0000019 秒进行调用。
当我更改方法的位置时,第二种方法比第一种方法花费的时间更多!原因是什么?
【问题讨论】:
-
等等,你是说你调用的第一个方法比较慢吗?因为看起来您的第二个示例输出是第一个复制粘贴的,而不是您在更改 调用 的顺序后运行代码的结果。 (它仍然在
method2之前列出method1。)在这种情况下,呃,在第二次调用时,它的代码可能在CPU 缓存中或者已经JITted。 -
同意这2个方法有相同的
calculations,所以第一次调用总是比第二次慢,因为calculations可能在第一次调用后缓存在CPU缓存中。
标签: c#