Let's discuss different approaches to programming in JavaScript: using a style with createA
or similar is common, while using class A
or similar is also popular.
Would [creating different functions each time] be less efficient in terms of memory?
Yes, it would be slightly less efficient due to function objects and closure, but whether this impact is significant depends on other factors as well.
When using the class
, function objects for methods are reused by each instance of the class because they are inherited from the prototype:
class A {
constructor(name, date) {
this.nameDateString = name + date;
}
someMethod() {
return `${this.nameDateString} ${this.nameDateString}`;
}
addAnotherNameDateString(name, date) {
this.nameDateString += name + date;
}
}
const a1 = new A("Joe", new Date());
const a2 = new A("Mary", new Date());
console.log(a1.someMethod === a2.someMethod); // true
On the other hand, when using the createA
function, different function objects are created every time createA
is called:
const createA = (name, date) => {
let nameDateString = name + date;
const someMethod = () => {
return `${nameDateString} ${nameDateString}`;
}
const addAnotherNameDateString = (name, date) => {
nameDateString += name + date;
}
return { someMethod, addAnotherNameDateString };
}
const a1 = createA("Joe", new Date());
const a2 = createA("Mary", new Date());
console.log(a1.someMethod === a2.someMethod); // false
Objects created by createA
have a larger memory imprint compared to those created by new A
as they possess their own copies of function objects.
However, the code underlying these function objects will be reused by any decent JavaScript engine. For instance:
const a1 = createA("Joe", new Date());
const a2 = createA("Mary", new Date());
In this scenario, memory allocation might look something like the following diagram shows...
(For detailed explanation, refer to the original text)
Ultimately, if the memory efficiency is crucial for your application, measure the impact with real code and consider using tools like Memory tab in browser dev tools to monitor memory consumption based on your coding choices.