有这么两个类:

 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(1000020000, c);
}
public long testta(long c)
{
return t.test(1000020000, c);
}

 

Testziji()和testta(),那个调用耗时少呢?应该是testta()。因为testziji()要先调用自己的test()方法,然后再调用t.test()方法,而testta()直接调用t.test()就行了,少一次调用,当然要快了。当然,这只是猜测,还需要验证一下~

验证代码:

 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()方法还是快点,差距还是有滴~

相关文章:

  • 2022-12-23
  • 2021-08-02
  • 2022-12-23
  • 2021-06-16
  • 2021-08-12
  • 2018-12-04
  • 2021-09-18
  • 2021-12-12
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-05-19
  • 2022-12-23
  • 2021-04-26
  • 2021-11-11
相关资源
相似解决方案