---
name: performance-ts
description: TypeScript/JavaScript performance optimization, bundle size, runtime performance, and React optimization.
---
# Performance Optimization - TypeScript/JavaScript
## Profiling Tools
### Chrome DevTools
```javascript
// CPU profiling
console.profile('myOperation');
expensiveOperation();
console.profileEnd('myOperation');
// Memory profiling
// DevTools > Memory > Take heap snapshot
// Performance timeline
// DevTools > Performance > Record
```
### Node.js Profiling
```bash
# CPU profile
node --prof app.js
node --prof-process isolate-*.log > processed.txt
# Heap snapshot
node --inspect app.js
# Chrome DevTools > Memory > Take snapshot
# Trace events
node --trace-events-enabled app.js
```
### Benchmarking
```typescript
import { performance } from 'perf_hooks';
const start = performance.now();
expensiveOperation();
const end = performance.now();
console.log(`Took ${end - start}ms`);
// Or use benchmark.js
import Benchmark from 'benchmark';
const suite = new Benchmark.Suite();
suite
.add('Method A', () => methodA())
.add('Method B', () => methodB())
.on('cycle', (event: any) => console.log(String(event.target)))
.run();
```
## Bundle Optimization
### Code Splitting
```typescript
// Route-based splitting
const Dashboard = lazy(() => import('./Dashboard'));
const Settings = lazy(() => import('./Settings'));
function App() {
return (
}>
} />
} />
);
}
```
### Tree Shaking
```typescript
// Bad: Imports entire library
import _ from 'lodash';
_.debounce(fn, 300);
// Good: Import only what you need
import debounce from 'lodash/debounce';
debounce(fn, 300);
// Or use lodash-es for better tree shaking
import { debounce } from 'lodash-es';
```
### Dynamic Imports
```typescript
// Load on demand
async function loadChart() {
const { Chart } = await import('chart.js');
return new Chart(ctx, config);
}
// Conditional loading
if (user.isPremium) {
const { PremiumFeature } = await import('./PremiumFeature');
render();
}
```
### Bundle Analysis
```bash
# Webpack Bundle Analyzer
npm install --save-dev webpack-bundle-analyzer
# Add to webpack config
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin()
]
};
# Vite
npm install --save-dev rollup-plugin-visualizer
```
## Runtime Performance
### Avoid Unnecessary Re-renders (React)
```typescript
// Bad: Creates new object every render
// Good: Memoize
const style = useMemo(() => ({ margin: 10 }), []);
// Bad: Inline function
// Good: useCallback
const handleClick = useCallback(() => {
doSomething(id);
}, [id]);
```
### Virtualization
```typescript
// Bad: Render 10,000 items
{items.map(item => )}
// Good: Virtualize with react-window
import { FixedSizeList } from 'react-window';
{({ index, style }) => (
)}
```
### Debounce & Throttle
```typescript
// Debounce: Wait for input to stop
import { debounce } from 'lodash-es';
const handleSearch = debounce((query: string) => {
api.search(query);
}, 300);
// Throttle: Limit execution frequency
import { throttle } from 'lodash-es';
const handleScroll = throttle(() => {
updateScrollPosition();
}, 100);
```
### Web Workers
```typescript
// Offload CPU-intensive work
const worker = new Worker(new URL('./worker.ts', import.meta.url));
worker.postMessage({ data: largeDataset });
worker.onmessage = (event) => {
const result = event.data;
updateUI(result);
};
// worker.ts
self.onmessage = (event) => {
const result = expensiveComputation(event.data);
self.postMessage(result);
};
```
## Memory Optimization
### Avoid Memory Leaks
```typescript
// Bad: Event listener not removed
useEffect(() => {
window.addEventListener('resize', handleResize);
}, []); // Leak!
// Good: Cleanup
useEffect(() => {
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
// Bad: Timer not cleared
useEffect(() => {
const timer = setInterval(poll, 1000);
}, []); // Leak!
// Good: Cleanup
useEffect(() => {
const timer = setInterval(poll, 1000);
return () => clearInterval(timer);
}, []);
```
### WeakMap for Caches
```typescript
// Good: Garbage collected when keys are no longer referenced
const cache = new WeakMap