“Use low-cost operators as much as you can. Like C++ and C, Java supports a set of shorthand arithmetic operations, such as ++, - [sic], +=, -=, *=, and /=. Since they actually generate faster code, use them whenever possible.”
While reading around on the supject:
They do this because binary operations create temporary objects, while += etc don’t.
To demonstrate (primitives etc work the same way) here is a 3 dimensional vector += operation:
vector3 &operator += (const vector3 &rhs) {
x += rhs.x;
y += rhs.y;
z += rhs.z;
return *this;
}
Now, + has to do exactly the same thing, but it has to create a new temporary object and return them, so that a = b + c + d + e; will work and not effect the original value.
+ is implemented using += but has the extra temp overhead.
vector3 operator + (const vector3 &lhs, const vector3 &rhs) {
vector3 tmp(a);
tmp += b;
return tmp;
}
My question is there even a unit of time that can measure the difference in the two chunks of code? I’m not sure we can measure fractions of a second that small. But since it was brought up, we’ll dive into it.
If you are trying to add on to an existing object, any sane programmer worth his salt will do:
myVector += anotherVector;
It’s cleaner, more readable code. The only case where I’d have to use the + on its own would be:
someVector = myVector + anotherVector;
I don’t want to change the value of myVector, so I have to do it this way. I suppose you could type
someVector += myVector;
someVector += anotherVector;
But I’d be afraid of being laughed out of the office for claiming that such code makes my program run faster. If this is the only way you can speed up your program, then either you have some great, efficient code, or you’ve really missed something during development.
Excerpted from Information Technology and Management