for(int i = 100000; i > 0; i–) {}
for(int i = 1; i < 100001; i++) {}
for(int i = 1; i < 100001; i++) {}
解决方案 »
- javamail邮件系统源代码下载(b/s)
- 问个关于frame的问题 [在线等]
- 怎么才能在JTable的单元格里添加数据呢,我想添加的是Properties文件里的数据。
- 关于数据集群的问题。急!!!!!!!!!!!!!!!!!!!!!!1
- 运用反射调用,如何传递参数?
- java里头int型数据,比如2005,显示出来是2,005,怎么把它变成2005?
- 考考你:有没有好主意实现在客户端的web页面显示一个按服务器的时间运行的时钟 注:不给分
- 简单问题:从Frame1调用Frame2,怎么让Frame2中的Button1不可用?
- 手机程序
- 关于字符串数组的值的问题
- 图形沿着鼠标轨迹移动
- java的awt图形界面的右上角关闭按钮不能使用
有这时间研究一下java的内存模型 原理什么的
{
public static void main(String[] args)
{
int count1=0,count2=0;
for(int i = 100000; i > 0; i--) {count1++;}
for(int i = 1; i < 100001; i++) {count2++;}
System.out.println(count1+" "+count2);
}
}
100000 100000
public class ForTest { /**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根 long t1 = System.currentTimeMillis();
for(int i = 1000000000; i > 0; i--) {}
long t2 = System.currentTimeMillis();
System.out.println(t2-t1);
long t3 = System.currentTimeMillis();
for(int i = 1; i < 1000000001; i++) {}
long t4 = System.currentTimeMillis();
System.out.println(t4-t3);
}}
运行结果1:
3055
1874运行结果2:
3336
1889运行结果3:
2914
1883
int count1 = 0, count2 = 0;
long time = System.currentTimeMillis();
for (int i = 100000; i > 0; i--) {
count1++;
}
System.out.println(System.currentTimeMillis() - time);
time = System.currentTimeMillis();
for (int i = 1; i < 100001; i++) {
count2++;
}
System.out.println(System.currentTimeMillis() - time);
println是 0,0后面我把循环放大了10000倍。
结果是1140,1125我记得以前看过,应该是+比-快,*比/快。
你换成
public class ForTest { /**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根 long t3 = System.currentTimeMillis();
for(int i = 1; i < 1000000001; i++) {}
long t4 = System.currentTimeMillis();
System.out.println(t4-t3); long t1 = System.currentTimeMillis();
for(int i = 1000000000; i > 0; i--) {}
long t2 = System.currentTimeMillis();
System.out.println(t2-t1);
}}
运行看看
具体原因我在下边帖里说过
http://topic.csdn.net/u/20100526/09/54b69af7-de38-44e5-aff9-a15fca4b2407.html
public class Test { public static void main(String[] args) throws InterruptedException {
long t3 = System.currentTimeMillis();
for(long i = 1; i < 20000000001l; i++) {
}
long t4 = System.currentTimeMillis();
System.out.println(t4 - t3); long t1 = System.currentTimeMillis();
for(long i = 20000000000l; i > 0; i--) {
}
long t2 = System.currentTimeMillis();
System.out.println(t2 - t1); }
}
75678
50289
性能差别可能就在 i>0 和 i<10001 上。
jvm指令前者用 ifgt ,直接判断是否大于0
后者用 if_icmpgt,需要和10001做比较最终被JIT翻译成本机代码也会不同,显然i>0效率更高。但这点儿差别可以忽略不计,java里更需要优化的地方多着呢。
14750
9531
一直保持在相差50%左右 至少对我这个测试环境来说已经是成立了 还有什么其他原因吗怕两者顺序的影响,分别起程序单独测
--一直稳定在10000
++一直稳定在15000对这个特定测试环境来说速度差值保持在一个较稳定的水平