Interesting exploration of i++ and ++i in Java
2月 24, 2020
·
1 分钟阅读时长
An interesting discover of using i++
and ++i
in Java loop
In general cases,
i++
in Java means use the value ofi
and increase it by 1 after finish.++i
in Java means firstly increasei
by 1 and use it afterwards
E.g.
int i = 1;
int output1 = i++;
i = 1;
int output2 = ++i;
System.out.println(output1);
System.out.println(output2);
Output:
1
2
However, in for loop:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
And:
for (int i = 1; i <= 5; ++i) {
System.out.println(i);
}
The output are both:
1
2
3
4
5
These two methods can basically be rewritten as:
for (int i = 1; i <= 5;) {
System.out.println(i);
i++; // or ++i
}
After searching for reasons, a developer introduces in a blog that though the output for using i++
and ++i
are the same, i++
needs a temporary variable to store the origin value before increasing, while there is no such a process in ++i
. Therefore, the running time of i++
is longer than ++i
, which is shown in the blog.
This shows that we should use ++i
instead of i++
, which can somehow improve the performance.