有这么两个类:
代码
Testziji()和testta(),那个调用耗时少呢?应该是testta()。因为testziji()要先调用自己的test()方法,然后再调用t.test()方法,而testta()直接调用t.test()就行了,少一次调用,当然要快了。当然,这只是猜测,还需要验证一下~
有这么两个类:
Code
class A
{
public long test(long a, long b, long c)
{
return a + b + c;
}
}
class B
{
private A t = new A();
private long test(long a, long b, long c)
{
return t.test(a, b, c);
}
public long testziji(long c)
{
return test(10000, 20000, c);
}
public long testta(long c)
{
return t.test(10000, 20000, c);
}
Testziji()和testta(),那个调用耗时少呢?应该是testta()。因为testziji()要先调用自己的test()方法,然后再调用t.test()方法,而testta()直接调用t.test()就行了,少一次调用,当然要快了。当然,这只是猜测,还需要验证一下~
验证代码:
Code
class Program
{
static void Main(string[] args)
{
long count = 1;
B ce = new B();
Stopwatch sp = new Stopwatch();
sp.Start();
for (long i = 0; i < count; i++)
{
ce.testziji(i);
}
sp.Stop();
Console.WriteLine("testziji()调用" + count .ToString()+ "次共耗时:" + sp.ElapsedTicks);
sp.Reset();
sp.Start();
for (long i = 0; i < count; i++)
{
ce.testta(i);
}
sp.Stop();
Console.WriteLine(" testta()调用" + count .ToString()+ "次共耗时:" + sp.ElapsedTicks);
Console.Read();
}
我验证了3次,以下是结果:
验证了我们的猜想,testta()方法还是快点,差距还是有滴~