0

Data structure and algorithm - time complexity (loop)

Hello, I don't know if this is the right place to ask this question but does using pre/post increment in loop has different effect/results in time complexity? Example: First scenario: for (int i = 0; i < 5; ++i) system.out.println("hello"); second scenario: for (int i = 0; i < 5; i++) System.out.println("hello"); 1st scenario is using pre increment so it doesn't need a copy to increment var i 2nd scenario is using post increment so it takes copy to the previous i value before moving to the next line. If the loops ended, does incrementation still do it's job? or it depends on the pre/post increment? Thank you! Ps: not good in English huhu.

28th Nov 2021, 3:06 PM
Kakai
Kakai - avatar
5 Answers
+ 2
"If the loop ended, does incrementation still do its job?" In this case I guess not, cause for both examples, loop counter <i> is scoped within the loop, <i> is not recognizable outside the loop. If <i> was defined outside the loop, you may notice a difference.
28th Nov 2021, 3:51 PM
Ipang
+ 2
Alexey Kopyshev In Java both ++i and i++ variants in loop will give no difference in speed, because Java code translates into intermediate byte code. What you said is actual in C/C++ world and nowadays C compilers smart enough with optimization flags.
28th Nov 2021, 5:38 PM
Ilyas Bakirov
Ilyas Bakirov - avatar
+ 1
In Java it makes no difference, but logically ++i should be faster, because in the i++ case the result is cached first and then used. For sure you can try to estimate it: Instant start = Instant.now(); for(int i=0; i<1000000000; i++){} Instant finish = Instant.now(); long timeElapsed = Duration.between(start, finish).toNanos(); System.out.println(timeElapsed);
28th Nov 2021, 3:34 PM
Alexey Kopyshev
Alexey Kopyshev - avatar
+ 1
Ilyas Bakirov yep, that's what I said right off the bat: There's no difference. This is about the hypothetical possibility.
28th Nov 2021, 6:08 PM
Alexey Kopyshev
Alexey Kopyshev - avatar