Very simple code performance

Possible duplicate:
Is there any performance difference between i ++ and i ++ in C ++?

Can someone explain to me why ++ I am faster than I ++ when we want to increase the integer value I assume that this can apply to any programming language.

0
source share
3 answers

This is absolutely not the case. This is such a common mistake that somehow continues to persist.

Note that when β€œi” is an object and assignment is performed, β€œi ++” will call a copy of this object (value before ++), while β€œ++ i” will not. Modern compilers will not execute a copy of an object if it is not needed.

+1
source

Let’s do (meaningless) benchmarking to show that it doesn’t matter:

Test code: (Java)

public class TestIncrement { public static void main(String[] av) { int x = 0; int y = 0; long startTime; // Postincrement startTime = System.currentTimeMillis(); while ( startTime + 1000 > System.currentTimeMillis()) { x++; } // Preincrement startTime = System.currentTimeMillis(); while ( startTime + 1000 > System.currentTimeMillis()) { ++y; } // Output System.out.println("Postincrement: " + x); System.out.println("Preincrement: " + y); } } 

And the conclusion:

 Postincrement: 16039755 Preincrement: 16069900 
+1
source

If you have an expression like

k = i ++;

k gets the old value of i before the increment, and i increases. This copy creates a performance impact and is not required with pre-incrementation. But sometimes both of them are not interchangeable. In this example with

k = ++ i;

you will get a different value for k.

0
source

Source: https://habr.com/ru/post/1402267/


All Articles