Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
Have lots of immutable objects or a few mutable ones?

I have a Point class that represents x and y coordinates. One approach is to make the properties of that class immutable and constantly create new objects when needed, like so:

class Point {
    readonly x: number;
    readonly y: number;

    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }

    add(x: number, y: number) {
        return new Point(this.x + x, this.y + y);
    }
}

document.addEventListener("mousemove", (e) => {
    let p = new Point(e.clientX, e.clientY);
    let p2 = p.add(24, 42);
    // ...
});

Another approach is to create objects beforehand and reuse them, for example:

class Point {
    x: number;
    y: number;

    constructor(x?: number, y?: number) {
        this.set(x, y);
    }

    set(x: number, y: number) {
        this.x = x;
        this.y = y;
    }

    add(x: number, y: number) {
        this.set(this.x + x, this.y + y);
    }

    copy(p: Point) {
        this.set(p.x, p.y)
        return this;
    }
}

let p = new Point();
let p2 = new Point();

document.addEventListener("mousemove", (e) => {
    p.set(e.clientX, e.clientY);
    p2.copy(p).add(24, 42)
    // ...
});

My theory is that since JavaScript is garbage collected, following the first pattern and spewing objects shouldn't be a problem, as long as you don't leave references to them. However, I looked at how the popular Three.js library implements its Vector2 object which does basically the same as what I've shown above, and it follows the second pattern.

The first approach seems more maintainable and easy to use, but the second one is maybe more memory-efficient?

When talking about design patterns in general, it largely comes down to preference and opinion. My question is, in the context of JavaScript, is there a concrete reason to pick one or the other, or the performance differences are negligible?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!