4 ms·
> Mutable classes are a performance hack. Could you please clarify this point? I have no idea what you're trying to say.
by sakuronto 9y ago
> Mutable classes are a performance hack.
Could you please clarify this point? I have no idea what you're trying to say.
- jacques_chester 9y agoIt'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.
- sgift 9y agoImmutable classes are far easier to reason about than mutable classes. You run the constructor and know "this instance won't ever change again" - but it means if you want a change you need to create a copy with the changed data, which can be a performance problem if you have to do it very often. See the difference between GregorianCalendar (or Date) and the more current java date APIs. The new ones are immutable and every "mutable" operation returns a new object instead of changing the old one.