A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 王松朝 金牌黑马   /  2014-7-31 18:26  /  568 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 王松朝 于 2014-7-31 18:28 编辑

很奇怪的结果!!!!

测试程序如下
  1. public class Main {

  2.         public static void main(String[] args){

  3.                 long ti = System.currentTimeMillis();
  4.                 for(int i=Integer.MIN_VALUE;i<Integer.MAX_VALUE;i++){
  5.                     if(i==i) continue;
  6.                 }
  7.                 System.out.println(System.currentTimeMillis()-ti);
  8.                

  9.                 ti = System.currentTimeMillis();
  10.                 for(int i=Integer.MIN_VALUE;i<Integer.MAX_VALUE;i++){
  11.                     continue;
  12.                 }
  13.                 System.out.println(System.currentTimeMillis()-ti);
  14.         }

  15. }
复制代码


输出结果
  1. 6
  2. 1320
复制代码


在for循环中加入判断后,循环执行的时间竟然差这么多。。

以上是问题,看下面这个测试,你会发现更有意思
  1. public class Main {

  2.         public static void main(String[] args){
  3.                
  4.                 long ti = System.currentTimeMillis();
  5.                 long c = 0;
  6.                 for(int i=Integer.MIN_VALUE;i<Integer.MAX_VALUE;i++){
  7.                     c++;
  8.                     if(i==i) continue;
  9.                 }
  10.                 System.out.println(System.currentTimeMillis()-ti + "  "+c);
  11.                
  12.                 ti = System.currentTimeMillis();
  13.                 c=0;
  14.                 for(int i=Integer.MIN_VALUE;i<Integer.MAX_VALUE;i++){
  15.                     c++;
  16.                     continue;
  17.                 }
  18.                 System.out.println(System.currentTimeMillis()-ti+ "  "+c);
  19.         }

  20. }
复制代码


同样输出
  1. 93  4294967295
  2. 7847  4294967295
复制代码


仅仅是在循环内做了一次++操作,耗时竟然增加了近10倍!不得不说,java!你的运行效率实在是惨不忍睹。。。。java版本:  javac 1.7.0_25

求解释:
在for循环中加入判断与不加判断,执行时间相差为什么会相差200倍?!

注:转自我的blog


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马