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.
Does
Testoneactually create a new anonymous function each time? IsTesttwotherefor more efficient or is it also creating separate instances ofdoWhatever?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)
