Performance Considerations
You'll learn when to worry about the performance differences between factory functions and classes, and what those differences actually are.
Memory and Performance Tradeoffs
Factory functions and classes create objects differently under the hood. With classes (or constructor functions), methods are defined once on the prototype and shared across all instances. With factory functions returning object literals, each object gets its own copy of every method.
// Class: methods shared via prototype
class User {
constructor(name) {
this.name = name;
}
greet() { return `Hi, ${this.name}`; }
}
// One greet function in memory, shared by all instances
// Factory: methods duplicated per instance
function createUser(name) {
return {
name,
greet() { return `Hi, ${this.name}`; }
};
}
// Each object has its own greet function copy
When Does It Actually Matter?
In most real-world applications, you'll never notice the difference. Modern JavaScript engines are highly optimized. Performance concerns become relevant when:
- Creating thousands or millions of objects (games, data processing)
- Running on resource-constrained devices (older phones, IoT)
- Building memory-sensitive applications (long-running processes)
For typical web apps creating dozens or hundreds of objects, choose the pattern that makes your code clearer. The readability and maintainability benefits of factory functions with closures often outweigh tiny memory overhead.
Key Takeaway: Classes are more memory-efficient for large numbers of objects, but factories are rarely slow enough to matter—choose based on your code's needs, not premature optimization.