-2

I'm reading C++ 101 Rules Guidelines and Best Practices, and at item 28, they state that post increment operator should be avoided if we don't need the old value of the variable, as this operator creates a copy of it, hence a tiny performance loss.

I was wondering if Java did this operation the same way, in which case prefix operator should also be prefered for for-loop statements (the ones that might not be suited to a for-each or a lambda forEach() statement)

Java specs tell (§15.14.2):

The value of the postfix increment expression is the value of the variable before the new value is stored

So, is there some new object created at any time during the operation ? As we're returning something different than the variable that's been incremented.

Barry
  • 286,269
  • 29
  • 621
  • 977
Webster
  • 164
  • 3
  • Are you using the operator on primitive values or the numeric reference type values? – Savior Apr 13 '16 at 15:41
  • Yes, after postfix increment there are 2 objects in memory - new and old value. Old value is result of expression. – Ivan Apr 13 '16 at 15:45
  • In general, these sorts of micro-optimization questions are meaningless in Java, since there is run-time optimization in the JVM. – azurefrog Apr 13 '16 at 15:45
  • True, didn't see that one when searching if this was already asked – Webster Apr 13 '16 at 15:51

1 Answers1

0

Yes, there is. This method might explain it:

int iplusplus(int i){ //this is just an example. in real java, this would be a copy of i
  int old = i; //this is the copy that might be unneeded
  i = i+1;     //this is the actual increment
  return old; 
}

old is the copied value. If you just want to increment i, ++i is shorter:

int plusplusi(int i){
  return i+1;
}

As mentioned, this method is not the same, as the parameter i would be a copy and you would not change the variable's value in the calling code.

f1sh
  • 11,489
  • 3
  • 25
  • 51