日期:2014-05-20  浏览次数:20781 次

为什么java里if else比三元运算快??
我写了两个类来测试速度:

Test:
public   class   Test   {

public   static   void   main(String   args[])
{
long   time   =   System.currentTimeMillis();

for(long   i=0;   i <   2000000000;   i++)
{
if(false){String   s   =   null;}
    else{String   s   =   null;};
}

System.out.println( " 'if   else ':用时 "+(System.currentTimeMillis()-time)/1000.0+ "秒 ");
}
}

Test2:


public   class   Test2   {

public   static   void   main(String   args[])
{
long   time   =   System.currentTimeMillis();

for(double   i=0;   i <   2000000000;   i++)
{
String   s   =   false?null:null;
}

System.out.println( " '三元运算符 ':用时 "+(System.currentTimeMillis()-time)/1000.0+ "秒 ");
}
}


运行结果if   else比三元运算快,试了好几次了,都一样,为什么?

------解决方案--------------------
ls是说我吗?

我的那段代码是对比三元运算符和if...else...(sun jdk),而不是试图说明三元运算符如何boxing/unboxing如何convert strong type,三元运算符对这些的处理没什么特别之处

对于其他代码,结果应该是类似的