
Memory Optimization
- 494 installs
- 305 repo stars
- Updated March 4, 2026
- aj-geddes/useful-ai-prompts
memory-optimization is a performance debugging skill that reduces heap usage, memory leaks, and garbage-collection pressure for developers profiling services, mobile clients, or CLI tools under load.
About
memory-optimization is an aj-geddes/useful-ai-prompts skill focused on diagnosing and reducing heap consumption, memory leaks, and garbage-collection pressure. Developers reach for it when services, mobile clients, or CLI tools spike memory under load or during long-running sessions and need structured profiling guidance rather than ad-hoc fixes. The skill supports performance work across backend services and client runtimes where RSS growth, retained objects, or GC thrashing degrade stability. Use it during profiling passes, pre-release performance reviews, or incident response where memory is the bottleneck. It complements CPU profiling by targeting allocation patterns, leak sources, and GC tuning strategies.
- Leak and retention diagnostics
- Allocation hotspot analysis
- Caching and pooling strategies
- GC-friendly data structure guidance
- Load-test memory benchmarks
Memory Optimization by the numbers
- 494 all-time installs (skills.sh)
- Ranked #837 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/aj-geddes/useful-ai-prompts --skill memory-optimizationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 494 |
|---|---|
| repo stars | ★ 305 |
| Last updated | March 4, 2026 |
| Repository | aj-geddes/useful-ai-prompts ↗ |
How do you fix memory leaks and high heap usage?
Reduce heap usage, leaks, and GC pressure when profiling services, mobile clients, or CLI tools that spike memory under load or long sessions.
Who is it for?
Backend and mobile developers profiling memory spikes, leaks, or GC thrashing in production-like load or long-session scenarios.
Skip if: Developers optimizing CPU-only bottlenecks, network latency, or database query performance without memory-related symptoms.
When should I use this skill?
User reports heap spikes, memory leaks, rising RSS, or GC pressure while profiling services, mobile apps, or CLI tools.
What you get
Reduced heap footprint, identified leak sources, and lower garbage-collection pressure profile
Files
Memory Optimization
Table of Contents
Overview
Memory optimization improves application performance, stability, and reduces infrastructure costs. Efficient memory usage is critical for scalability.
When to Use
- High memory usage
- Memory leaks suspected
- Slow performance
- Out of memory crashes
- Scaling challenges
Quick Start
Minimal working example:
// Browser memory profiling
// Check memory usage
performance.memory: {
jsHeapSizeLimit: 2190000000, // Max available
totalJSHeapSize: 1300000000, // Total allocated
usedJSHeapSize: 950000000 // Currently used
}
// React DevTools Profiler
- Open React DevTools → Profiler
- Record interaction
- See component renders and time
- Identify unnecessary renders
// Chrome DevTools
1. Open DevTools → Memory
2. Take heap snapshot
3. Compare before/after
4. Look for retained objects
5. Check retained sizes
// Node.js profiling
node --inspect app.js
// Open chrome://inspect
// ... (see reference guides for full implementation)Reference Guides
Detailed implementations in the references/ directory:
| Guide | Contents |
|---|---|
| Memory Profiling | Memory Profiling |
| Memory Leak Detection | Memory Leak Detection |
| Optimization Techniques | Optimization Techniques |
| Monitoring & Targets | Monitoring & Targets |
Best Practices
✅ DO
- Follow established patterns and conventions
- Write clean, maintainable code
- Add appropriate documentation
- Test thoroughly before deploying
❌ DON'T
- Skip testing or validation
- Ignore error handling
- Hard-code configuration values
Memory Leak Detection
Memory Leak Detection
# Identify and fix memory leaks
class MemoryLeakDebug:
def identify_leaks(self):
"""Common patterns"""
return {
'circular_references': {
'problem': 'Objects reference each other, prevent GC',
'example': 'parent.child = child; child.parent = parent',
'solution': 'Use weak references or cleaner code'
},
'event_listeners': {
'problem': 'Listeners not removed',
'example': 'element.addEventListener(...) without removeEventListener',
'solution': 'Always remove listeners on cleanup'
},
'timers': {
'problem': 'setInterval/setTimeout not cleared',
'example': 'setInterval(() => {}, 1000) never clearInterval',
'solution': 'Store ID and clear on unmount'
},
'cache_unbounded': {
'problem': 'Cache grows without bounds',
'example': 'cache[key] = value (never deleted)',
'solution': 'Implement TTL or size limits'
},
'dom_references': {
'problem': 'Removed DOM elements still referenced',
'example': 'var x = document.getElementById("removed")',
'solution': 'Clear references after removal'
}
}
def detect_in_browser(self):
"""JavaScript detection"""
return """
// Monitor memory growth
setInterval(() => {
const mem = performance.memory;
const used = mem.usedJSHeapSize / 1000000;
console.log(`Memory: ${used.toFixed(1)} MB`);
}, 1000);
// If grows over time without plateau = leak
"""Memory Profiling
Memory Profiling
// Browser memory profiling
// Check memory usage
performance.memory: {
jsHeapSizeLimit: 2190000000, // Max available
totalJSHeapSize: 1300000000, // Total allocated
usedJSHeapSize: 950000000 // Currently used
}
// React DevTools Profiler
- Open React DevTools → Profiler
- Record interaction
- See component renders and time
- Identify unnecessary renders
// Chrome DevTools
1. Open DevTools → Memory
2. Take heap snapshot
3. Compare before/after
4. Look for retained objects
5. Check retained sizes
// Node.js profiling
node --inspect app.js
// Open chrome://inspect
// Take heap snapshots
// Compare growth over timeMonitoring & Targets
Monitoring & Targets
Memory Targets:
Web App:
Initial: <10MB
After use: <50MB
Peak: <100MB
Leak check: Should plateau
Node.js API:
Per-process: 100-500MB
Cluster total: 1-4GB
Heap size: Monitor vs available RAM
Mobile:
Initial: <20MB
Working: <50MB
Peak: <100MB (device dependent)
---
Tools:
Browser:
- Chrome DevTools Memory
- Firefox DevTools Memory
- React DevTools Profiler
- Redux DevTools
Node.js:
- node --inspect
- clinic.js
- nodemon --exec with monitoring
- New Relic / DataDog
Monitoring:
- Application Performance Monitoring (APM)
- Prometheus + Grafana
- CloudWatch
- New Relic
---
Checklist:
[ ] Profile baseline memory
[ ] Identify heavy components
[ ] Remove event listeners on cleanup
[ ] Clear timers on cleanup
[ ] Implement lazy loading
[ ] Use pagination for large lists
[ ] Monitor memory trends
[ ] Set up GC monitoring
[ ] Test with production data volume
[ ] Stress test for leaks
[ ] Establish memory budget
[ ] Set up alertsOptimization Techniques
Optimization Techniques
Memory Optimization:
Object Pooling:
Pattern: Reuse objects instead of creating new
Example: GameObject pool in games
Benefits: Reduce GC, stable memory
Trade-off: Complexity
Lazy Loading:
Pattern: Load data only when needed
Example: Infinite scroll
Benefits: Lower peak memory
Trade-off: Complexity
Pagination:
Pattern: Process data in chunks
Example: 1M records → 1K per page
Benefits: Constant memory
Trade-off: More requests
Stream Processing:
Pattern: Process one item at a time
Example: fs.createReadStream()
Benefits: Constant memory for large data
Trade-off: Slower if cached
Memoization:
Pattern: Cache expensive calculations
Benefits: Faster, reuse results
Trade-off: Memory for speed
---
Framework-Specific:
React:
- useMemo for expensive calculations
- useCallback to avoid creating functions
- Code splitting / lazy loading
- Windowing for long lists (react-window)
Node.js:
- Stream instead of loadFile
- Limit cluster workers
- Set heap size: --max-old-space-size=4096
- Monitor with clinic.js
---
GC (Garbage Collection):
Minimize:
- Object creation
- Large allocations
- Frequent new objects
- String concatenation
Example (Bad):
let result = "";
for (let i = 0; i < 1000000; i++) {
result += i.toString() + ",";
// Creates new string each iteration
}
Example (Good):
const result = Array.from(
{length: 1000000},
(_, i) => i.toString()
).join(",");
// Single allocation// Component: [Name]
// TODO: Customize for your framework (React, Vue, Svelte, etc.)
import React from 'react';
interface Props {
// TODO: Define props
}
export function ComponentName({ }: Props) {
// TODO: Add state and effects
return (
<div>
{/* TODO: Add component markup */}
</div>
);
}
Related skills
How it compares
Use memory-optimization for heap and GC issues; pick CPU or database profiling skills when memory metrics are not the bottleneck.
FAQ
What runtimes does memory-optimization cover?
memory-optimization addresses heap usage, leaks, and GC pressure in backend services, mobile clients, and CLI tools. It fits profiling under load or during extended sessions where memory grows unexpectedly.
When should I invoke memory-optimization?
memory-optimization fits when profiling shows heap spikes, memory leaks, rising RSS, or GC thrashing. Skip it when the bottleneck is CPU, network, or database query latency without memory symptoms.