Run details:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36
Chrome 94
Windows
Desktop
3 years ago
Test name Executions per second
cloneWith 549301.3 Ops/sec
cloneWith2 768467.2 Ops/sec
mutate 1027458.9 Ops/sec
Script Preparation code:
x
 
class Holder {
    constructor(init) {
        Holder.internalAssign(this, init);
    }
    static has(instance, property) {
        return Object.prototype.hasOwnProperty.call(instance, property);
    }
    static internalAssign(target, source) {
        if (Holder.has(source, "a"))
            target.a = source.a;
        if (Holder.has(source, "b"))
            target.b = source.b;
        if (Holder.has(source, "c"))
            target.c = source.c;
    }
    clone() {
        return new Holder(this);
    }
    cloneWith(props) {
        const cloned = this.clone();
        Holder.internalAssign(cloned, props);
        return cloned;
    }
    cloneWith2(props) {
        const cloned = this.clone();
        Object.assign(this, props);
        return cloned;
    }
    mutate(mutation) {
        const cloned = this.clone();
        mutation(cloned);
        return cloned;
    }
}
var initHolder = new Holder({
    a: "value of a",
    b: "value of b",
    c: 1
});
Tests:
  • cloneWith

     
    initHolder.cloneWith({ a: "changed a", b: "changed b" });
  • cloneWith2

     
    initHolder.cloneWith2({ a: "changed a", b: "changed b" });
  • mutate

     
    initHolder.mutate(x => { x.a = "changed a"; x.b = "changed b" });