snippetjavascriptModeratepending
JavaScript Proxy-based lazy initialization -- defer expensive operations
Viewed 0 times
lazy initializationProxydeferredstartup timeon-demand
nodejsbrowser
Problem
Initializing all services, connections, and heavy objects at startup slows down application start time. Many of these may never be used in a given request.
Solution
Use Proxy to defer initialization until first access. The proxy transparently forwards all operations to the lazily-created real object.
Code Snippets
Lazy initialization with Proxy
function lazy(factory) {
let instance = null;
return new Proxy({}, {
get(_, prop) {
if (!instance) instance = factory();
const value = instance[prop];
return typeof value === 'function' ? value.bind(instance) : value;
},
});
}
// Usage: database connection created on first query
const db = lazy(() => {
console.log('Connecting to database...');
return new DatabaseClient(config);
});
// Nothing happens yet...
console.log('App started');
// NOW the connection is created:
const users = await db.query('SELECT * FROM users');Revisions (0)
No revisions yet.