Home > database >  Local function declaration versus pointer to function
Local function declaration versus pointer to function

Time:09-19

class Testone{
    constructor(value){
        Object.defineProperty(this, 'doSomething', {
            enumerable: false,
            configurable: false,
            writable: false,
            value: () => {
                //do whatever
            }
        });
    }
} 

const doWhatever = () => {
    //do whatever
} 

class Testtwo{
    constructor(value){
        Object.defineProperty(this, 'doSomething', {
            enumerable: false,
            configurable: false,
            writable: false,
            value: doWhatever
        });
    }
}

My thought is that Testtwo should be more efficient, since doWhatever would only exist in memory once then get pointed to by every instance of Testtwo. Testone would instantiate a new anonymous function for each new instance.

  1. Does Testone actually create a new anonymous function each time? Is Testtwo therefor more efficient or is it also creating separate instances of doWhatever?

  2. Am I missing some major caveat to one over the other (other than variable scope)?

My benchmarking consistently shows ~2% difference in instantiation time, with Testtwo indeed being faster... but that's not exactly confirmation.

CodePudding user response:

Yes. Testone create new doSomething function every time, but Testtwo uses existing one.

Proof:

class Testone{
    constructor(value){
        Object.defineProperty(this, 'doSomething', {
            enumerable: false,
            configurable: false,
            writable: false,
            value: () => {
                //do whatever
            }
        });
    }
} 

const doWhatever = () => {
    //do whatever
}

class Testtwo{
    constructor(value){
        Object.defineProperty(this, 'doSomething', {
            enumerable: false,
            configurable: false,
            writable: false,
            value: doWhatever
        });
    }
}

const f1 = new Testone()
const f2 = new Testone()
console.log('Testone', f1.doSomething === f2.doSomething)

const s1 = new Testtwo()
const s2 = new Testtwo()
console.log('Testtwo', s1.doSomething === s2.doSomething)

  • Related