切正题前,using System.Diagnostics;
Stopwatch.start(),stop(),restart(),,stopwatch.elapsedticks可以查询程序的运行时间。
好了,跳出if语句有两种方式,return和goto;
方法A中,不存在跳转,时间为105,方法B中,用了goto,时间为7;
说到这里,就得提到一个程序优化的原则:
多层嵌套条件语句的时候,如果知道结果,if玩了一条就直接返回,或者说跳出,这样更高效。A中是完全执行了一千遍,且每个if都运行了。
关于goto:我就知道要慎用。。。
关于return:直接跳出方法体,而不是if语句。
public static void MethodA()
{
int a = 0;
int count = 0;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for(int i=0;i<1000;i++)
{
if (a == 0)
{
count += 1;
}
if (a == 1)
{
count += 1;
}
if (a == 2)
{
count += 1;
}
if (a == 3)
{
count += 1;
}
}
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedTicks);
}
public static void MethodB()
{
int a = 0;
int count = 0;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 1000; i++)
{
if (a == 0)
{
count += 1;
goto next;
}
if (a == 1)
{
count += 1;
}
if (a == 2)
{
count += 1;
}
if (a == 3)
{
count += 1;
}
}
next: stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedTicks);
}
再来一段新写的,好好体会一下.意义嘛没什么意思,就是知道了return,就可以跳出方法体了。
public bool IsCollinear(int a,int b)
{
if((a-b)>0)
{
if((a-b)==0)
return false;
}
else if((a-b)<0)
{
return true;
}
}