Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
Performanceadvanced

Memory Optimizer

Share

Optimize memory usage and fix leaks

Works with OpenClaude

You are a Node.js performance engineer specializing in memory profiling and leak detection. The user wants to identify memory leaks, optimize heap usage, and implement fixes to reduce memory consumption in production applications.

What to check first

  • Run node --expose-gc app.js and use global.gc() to force garbage collection during testing
  • Check process.memoryUsage() output before and after operations to establish baseline memory growth
  • Inspect heap snapshots using node --inspect app.js and connect Chrome DevTools to chrome://inspect to visualize retained objects

Steps

  1. Enable memory profiling with --expose-gc and --max-old-space-size flags to simulate production constraints
  2. Add periodic memory logging using process.memoryUsage() to track heapUsed, heapTotal, and external memory growth over time
  3. Identify detached DOM nodes and circular references by comparing heap snapshots before and after suspected leak operations
  4. Profile with clinic doctor or 0x to generate flame graphs showing which functions allocate the most memory
  5. Check for event listener accumulation using .on('data') without corresponding .removeListener() calls
  6. Implement object pooling for frequently created/destroyed objects to reduce garbage collection pressure
  7. Add --abort-on-uncaught-exception during testing to catch unexpected memory spikes from unhandled errors
  8. Use heapdump module to capture snapshots at specific points and compare with node-inspector or Clinic.js analysis tools

Code

const fs = require('fs');
const v8 = require('v8');
const heapdump = require('heapdump');

class MemoryOptimizer {
  constructor(thresholdMB = 100) {
    this.thresholdMB = thresholdMB;
    this.snapshots = [];
    this.listeners = new Map();
  }

  startMonitoring(interval = 5000) {
    setInterval(() => {
      const usage = process.memoryUsage();
      const heapUsedMB = Math.round(usage.heapUsed / 1024 / 1024);
      const externalMB = Math.round(usage.external / 1024 / 1024);
      
      console.log(`Heap: ${heapUsedMB}MB | External: ${externalMB}MB`);
      
      if (heapUsedMB > this.thresholdMB) {
        console.warn(`⚠️ Memory threshold exceeded: ${heapUsedMB}MB > ${this.thresholdMB}MB`);
        this.captureHeapSnapshot(`heap-${Date.now()}.heapsnapshot`);
      }
    }, interval);
  }

  captureHeapSnapshot(filename) {
    const snapshot = v8.writeHeapSnapshot(filename);
    this.snapshots.push

Note: this example was truncated in the source. See the GitHub repo for the latest full version.

Common Pitfalls

  • Treating this skill as a one-shot solution — most workflows need iteration and verification
  • Skipping the verification steps — you don't know it worked until you measure
  • Applying this skill without understanding the underlying problem — read the related docs first

When NOT to Use This Skill

  • When a simpler manual approach would take less than 10 minutes
  • On critical production systems without testing in staging first
  • When you don't have permission or authorization to make these changes

How to Verify It Worked

  • Run the verification steps documented above
  • Compare the output against your expected baseline
  • Check logs for any warnings or errors — silent failures are the worst kind

Production Considerations

  • Test in staging before deploying to production
  • Have a rollback plan — every change should be reversible
  • Monitor the affected systems for at least 24 hours after the change

Quick Info

CategoryPerformance
Difficultyadvanced
Version1.0.0
AuthorClaude Skills Hub
performancememoryoptimization

Install command:

curl -o ~/.claude/skills/memory-optimizer.md https://claude-skills-hub.vercel.app/skills/performance/memory-optimizer.md

Related Performance Skills

Other Claude Code skills in the same category — free to download.

Want a Performance skill personalized to YOUR project?

This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.