为什么递减循环比递增循环运行得更快? [英] Why does decrement loop runs faster than increment loop?

查看:248
本文介绍了为什么递减循环比递增循环运行得更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在经历递增/递减运算符,而我遇到了如果我以递减形式运行循环,那么它将以递增形式运行得比同一循环更快。我期待两者都会花费相同的时间,因为将遵循相同数量的步骤。我在网上搜索但是找不到令人信服的答案。是否因为与递增运算符相比减量运算符花费的时间更少?

I was going through increment/decrement operators, and I encountered that if i run a loop in decremental form in that case it will run faster than the same loop in incremental form. I was expecting that both will take equal time since same amount of steps will be followed. I searched through the web but could not find convincing answer to this. Is it due to the case that decrement operator takes less time as compared to increment operator?

for(int i = 100000; i > 0; i--) {}
for(int i = 1; i < 100001; i++) {}


推荐答案

这是因为在字节码中,与0比较的操作与使用非零数字进行比较的操作不同。实际上 i< 10001 需要首先加载堆栈上的数字然后执行比较,而 i> 0 作为一个操作执行。当然,由于JVM优化,大多数情况下都没有速度差异。但我们可以尝试通过使用-Xint选项运行代码使其可见(仅限解释模式执行)。

This is because in bytecode comparison with 0 is a different operation than comparison with a non-zero number. Actually i < 10001 requires to first load the number on stack then execute comparison, while i > 0 is executed as one operation. Of course there will be no speed difference in most cases because of JVM optimizations. But we can try to make it visible by running the code with -Xint option (interpreted mode execution only).

这篇关于为什么递减循环比递增循环运行得更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆