Code Optimization
Learn advanced code optimization techniques for production JavaScript applications. This is a foundational concept in programming and web interactivity that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world JavaScript experience. Take your time with each section and practice the examples
Performance Optimization
Optimize JavaScript code for better performance, smaller bundle sizes, and faster execution.. This is an essential concept that every JavaScript developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Bundle Optimization
// webpack.config.js - Bundle optimization
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\/]node_modules[\/]/,
name: 'vendors',
chunks: 'all'
}
}
},
usedExports: true,
sideEffects: false
},
plugins: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
}
})
]
};Tree Shaking
// ES6 modules for tree shaking
// utils.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
export const divide = (a, b) => a / b;
// main.js
import { add } from './utils.js';
// Only 'add' function will be included in bundle
// CommonJS (not tree-shakeable)
const utils = require('./utils');
// Entire utils module will be includedLazy Loading
// Dynamic imports for lazy loading
const loadModule = async () => {
const module = await import('./heavy-module.js');
return module.default;
};
// React lazy loading
const LazyComponent = React.lazy(() => import('./HeavyComponent'));
// Route-based code splitting
const routes = [
{
path: '/',
component: () => import('./pages/Home')
},
{
path: '/about',
component: () => import('./pages/About')
}
];Memory Optimization
// Memory leak prevention
class DataProcessor {
constructor() {
this.cache = new Map();
this.cleanupInterval = setInterval(() => {
this.cleanupCache();
}, 60000); // Clean every minute
}
processData(data) {
const key = JSON.stringify(data);
if (this.cache.has(key)) {
return this.cache.get(key);
}
const result = this.expensiveOperation(data);
this.cache.set(key, result);
return result;
}
cleanupCache() {
// Remove old entries
const now = Date.now();
for (const [key, value] of this.cache) {
if (now - value.timestamp > 300000) { // 5 minutes
this.cache.delete(key);
}
}
}
destroy() {
clearInterval(this.cleanupInterval);
this.cache.clear();
}
}Mini-Project: Performance Optimizer
// Performance optimization utility
class PerformanceOptimizer {
static debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
static throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
static memoize(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
static imageOptimizer() {
return {
lazyLoad: (img) => {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const image = entry.target;
image.src = image.dataset.src;
observer.unobserve(image);
}
});
});
observer.observe(img);
},
compress: (file, quality = 0.8) => {
return new Promise((resolve) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
canvas.toBlob(resolve, 'image/jpeg', quality);
};
img.src = URL.createObjectURL(file);
});
}
};
}
}