3 ms·
It's often much faster to modify something in place than to create a modified copy. Suppose I have: Point point = new Point(50, 50); int x = 100;
by jacques_chester 9y ago
It's often much faster to modify something in place than to create a modified copy.
Suppose I have:
Point point = new Point(50, 50);
int x = 100;
int y = 200;
Point translatedPoint = point.plus(x, y); // new Point(this.x + x, this.y + y)
This code suggests that Point is immutable. Once defined, a point never changes. This makes a lot of sense -- if you change the values of x and y, you have a different point, in a mathematical sense.
But newing up an object is tremendously slower than integer arithmetic. Suppose I can do this:
Point point = new Point(50, 50);
point.translateX(100); // this.x += x
point.translateY(200); // this.y += y
Point translatedPoint = point;
This is going to lead to translatedPoint much more quickly than the first code. But it's riddled with troublesome outcomes. Who else was relying on point? What happens if I change it again? Why am I able to mutate something that, mathematically, isn't mutable?
The basic reason mutability improves performance is that you can change things in-place without making a new copy. Most of the stuff being done during the copy construction is overhead compared to the thing you're changing. The price might be too high in a performance-sensitive situation.
There are workarounds based on using copy-on-write datastructures with clever shared bits, but they're not native idioms in Java-land or in most languages without a strong functional heritage.