Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问clear审计通过

performance-optimization性能优化

Agent Skill

performance-optimization 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

865

周安装

35

GitHub Stars

12

下载量

272
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:performance-optimization(性能优化)
来源仓库:https://github.com/miles990/claude-software-skills
仓库路径:skills/performance-optimization
安装命令:
npx skills add https://github.com/miles990/claude-software-skills --skill performance-optimization
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/miles990/claude-software-skills --skill performance-optimization

简介

performance-optimization 用于查找、检索和筛选相关信息。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中根据关键词快速定位候选结果。
  • 通过 npx skills add 命令从指定仓库安装,需确认权限和维护状态。
  • 使用前建议核实是否会触发联网、命令执行或文件读写操作。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Performance Optimization

Overview

Measure first, optimize second. This guide covers profiling techniques and optimization strategies.


Profiling First

The Golden Rule

1. Don't optimize prematurely
2. Measure before optimizing
3. Optimize the biggest bottleneck first
4. Measure again to verify improvement

CPU Profiling (Node.js)

// Using Node.js built-in profiler
// Start with: node --prof app.js
// Process: node --prof-process isolate-*.log > profile.txt

// Or use clinic.js
// npm install -g clinic
// clinic doctor -- node app.js
// clinic flame -- node app.js

// Programmatic profiling
import { performance, PerformanceObserver } from 'perf_hooks';

const obs = new PerformanceObserver((items) => {
  items.getEntries().forEach((entry) => {
    console.log(`${entry.name}: ${entry.duration}ms`);
  });
});
obs.observe({ entryTypes: ['measure'] });

performance.mark('start');
await expensiveOperation();
performance.mark('end');
performance.measure('expensive-op', 'start', 'end');

Memory Profiling

// Check memory usage
console.log(process.memoryUsage());
// {
//   rss: 30000000,      // Resident Set Size - total memory
//   heapTotal: 7000000, // V8 heap total
//   heapUsed: 5000000,  // V8 heap used
//   external: 800000    // C++ objects bound to JS
// }

// Take heap snapshot
const v8 = require('v8');
const fs = require('fs');

const snapshotFile = `heap-${Date.now()}.heapsnapshot`;
const snapshot = v8.writeHeapSnapshot(snapshotFile);
// Open in Chrome DevTools Memory tab

Database Optimization

Query Optimization

-- ❌ Slow: SELECT * and no index
SELECT * FROM orders WHERE user_id = 123;

-- ✅ Better: Select only needed columns, with index
CREATE INDEX idx_orders_user_id ON orders(user_id);
SELECT id, total, status FROM orders WHERE user_id = 123;

-- ❌ N+1 query problem
-- For each user, query their orders (100 users = 101 queries)
SELECT * FROM users;
SELECT * FROM orders WHERE user_id = 1;
SELECT * FROM orders WHERE user_id = 2;
...

-- ✅ Single query with JOIN
SELECT u.*, o.* FROM users u
LEFT JOIN orders o ON u.id = o.user_id;

-- Or batch loading
SELECT * FROM orders WHERE user_id IN (1, 2, 3, ...);

Explain Analyze

EXPLAIN ANALYZE
SELECT u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at > '2024-01-01'
GROUP BY u.id
ORDER BY order_count DESC
LIMIT 10;

-- Output shows:
-- - Execution plan (Seq Scan vs Index Scan)
-- - Estimated vs actual rows
-- - Time per operation
-- - Total execution time

Index Strategies

-- Single column index
CREATE INDEX idx_users_email ON users(email);

-- Composite index (order matters!)
-- Good for: WHERE status = 'active' AND created_at > '2024-01-01'
CREATE INDEX idx_orders_status_created ON orders(status, created_at);

-- Partial index (smaller, faster for filtered queries)
CREATE INDEX idx_active_users ON users(email)
WHERE status = 'active';

-- Covering index (includes all needed columns)
CREATE INDEX idx_orders_user_covering ON orders(user_id)
INCLUDE (total, status, created_at);

-- When NOT to index:
-- - Small tables
-- - Columns with low cardinality (e.g., boolean)
-- - Frequently updated columns
-- - Write-heavy tables

Caching

Cache Strategies

// Cache-aside pattern
async function getUser(id: string): Promise<User> {
  // Try cache first
  const cached = await cache.get(`user:${id}`);
  if (cached) return JSON.parse(cached);

  // Cache miss - fetch from DB
  const user = await db.users.findById(id);

  // Store in cache
  if (user) {
    await cache.set(`user:${id}`, JSON.stringify(user), 'EX', 3600);
  }

  return user;
}

// Write-through pattern
async function updateUser(id: string, data: Partial<User>): Promise<User> {
  // Update DB
  const user = await db.users.update(id, data);

  // Update cache immediately
  await cache.set(`user:${id}`, JSON.stringify(user), 'EX', 3600);

  return user;
}

Cache Invalidation

// Event-based invalidation
eventBus.on('user:updated', async (userId: string) => {
  await cache.del(`user:${userId}`);
  await cache.del(`user:${userId}:orders`);
});

// Tag-based invalidation
async function invalidateUserRelated(userId: string) {
  const keys = await cache.keys(`*:user:${userId}:*`);
  if (keys.length > 0) {
    await cache.del(...keys);
  }
}

// Version-based cache busting
const CACHE_VERSION = 'v2';
const cacheKey = `${CACHE_VERSION}:user:${id}`;

Memoization

// Simple memoization
function memoize<T extends (...args: any[]) => any>(fn: T): T {
  const cache = new Map();

  return ((...args: Parameters<T>) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);

    const result = fn(...args);
    cache.set(key, result);
    return result;
  }) as T;
}

// With TTL
function memoizeWithTTL<T extends (...args: any[]) => any>(
  fn: T,
  ttlMs: number
): T {
  const cache = new Map<string, { value: any; expires: number }>();

  return ((...args: Parameters<T>) => {
    const key = JSON.stringify(args);
    const cached = cache.get(key);

    if (cached && cached.expires > Date.now()) {
      return cached.value;
    }

    const result = fn(...args);
    cache.set(key, { value: result, expires: Date.now() + ttlMs });
    return result;
  }) as T;
}

Frontend Performance

Core Web Vitals

MetricGoodDescription
LCP< 2.5sLargest Contentful Paint
INP< 200msInteraction to Next Paint
CLS< 0.1Cumulative Layout Shift

Code Splitting

// React lazy loading
import { lazy, Suspense } from 'react';

const Dashboard = lazy(() => import('./Dashboard'));
const Settings = lazy(() => import('./Settings'));

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <Routes>
        <Route path="/dashboard" element={<Dashboard />} />
        <Route path="/settings" element={<Settings />} />
      </Routes>
    </Suspense>
  );
}

// Dynamic import for heavy libraries
async function processImage(file: File) {
  const sharp = await import('sharp');
  return sharp(file).resize(800).toBuffer();
}

Image Optimization

<!-- Responsive images -->
<img
  src="image-800.jpg"
  srcset="
    image-400.jpg 400w,
    image-800.jpg 800w,
    image-1200.jpg 1200w
  "
  sizes="(max-width: 600px) 400px, 800px"
  loading="lazy"
  alt="Description"
/>

<!-- Modern formats with fallback -->
<picture>
  <source srcset="image.avif" type="image/avif" />
  <source srcset="image.webp" type="image/webp" />
  <img src="image.jpg" alt="Description" />
</picture>

Bundle Optimization

// webpack.config.js
module.exports = {
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all',
        },
        // Separate large libraries
        react: {
          test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
          name: 'react',
          chunks: 'all',
        },
      },
    },
  },
};

Backend Performance

Connection Pooling

// Database connection pool
import { Pool } from 'pg';

const pool = new Pool({
  max: 20,                    // Maximum connections
  idleTimeoutMillis: 30000,   // Close idle connections after 30s
  connectionTimeoutMillis: 2000, // Fail if can't connect in 2s
});

// Use pool, not individual connections
async function getUser(id: string) {
  const result = await pool.query('SELECT * FROM users WHERE id = $1', [id]);
  return result.rows[0];
}

// HTTP connection keep-alive
import http from 'http';

const agent = new http.Agent({
  keepAlive: true,
  maxSockets: 50,
});

fetch('https://api.example.com', { agent });

Async Processing

// Move slow operations out of request path
app.post('/api/orders', async (req, res) => {
  // Quick: Create order
  const order = await db.orders.create(req.body);

  // Don't wait: Queue async tasks
  await queue.add('send-confirmation-email', { orderId: order.id });
  await queue.add('update-inventory', { items: order.items });
  await queue.add('notify-warehouse', { orderId: order.id });

  // Respond immediately
  res.status(201).json(order);
});

// Process queue separately
queue.process('send-confirmation-email', async (job) => {
  const order = await db.orders.findById(job.data.orderId);
  await emailService.sendOrderConfirmation(order);
});

Response Compression

import compression from 'compression';
import express from 'express';

const app = express();

// Compress responses > 1KB
app.use(compression({
  threshold: 1024,
  filter: (req, res) => {
    if (req.headers['x-no-compression']) {
      return false;
    }
    return compression.filter(req, res);
  }
}));

Algorithm Optimization

Time Complexity

// O(n²) → O(n) with Set
// Find duplicates
function hasDuplicates(arr: number[]): boolean {
  // ❌ O(n²)
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j]) return true;
    }
  }
  return false;

  // ✅ O(n)
  const seen = new Set<number>();
  for (const num of arr) {
    if (seen.has(num)) return true;
    seen.add(num);
  }
  return false;
}

// O(n) → O(1) with Map
// Lookup by key
class UserCache {
  // ❌ O(n) lookup
  private users: User[] = [];

  find(id: string) {
    return this.users.find(u => u.id === id);
  }

  // ✅ O(1) lookup
  private usersMap = new Map<string, User>();

  findFast(id: string) {
    return this.usersMap.get(id);
  }
}

Space vs Time Tradeoff

// Trade memory for speed: Precompute
class TaxCalculator {
  private taxRates = new Map<string, number>();

  constructor() {
    // Precompute all tax rates
    for (const state of US_STATES) {
      this.taxRates.set(state, this.computeTaxRate(state));
    }
  }

  // O(1) instead of O(complex calculation)
  getTaxRate(state: string): number {
    return this.taxRates.get(state) ?? 0;
  }
}

Monitoring Performance

// Application metrics
import { Counter, Histogram } from 'prom-client';

const httpRequestDuration = new Histogram({
  name: 'http_request_duration_seconds',
  help: 'Duration of HTTP requests',
  labelNames: ['method', 'route', 'status'],
  buckets: [0.1, 0.5, 1, 2, 5]
});

app.use((req, res, next) => {
  const start = Date.now();

  res.on('finish', () => {
    const duration = (Date.now() - start) / 1000;
    httpRequestDuration
      .labels(req.method, req.route?.path || 'unknown', res.statusCode.toString())
      .observe(duration);
  });

  next();
});

Related Skills

  • [[database]] - Database optimization details
  • [[frontend]] - Frontend performance
  • [[monitoring-observability]] - Performance monitoring

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

30.11%
按下载量换算82

Antigravity

22.69%
按下载量换算62

Claude Code

17.43%
按下载量换算47

Gemini CLI

12.12%
按下载量换算33

windsurf

7.74%
按下载量换算21

Cursor

3.93%
按下载量换算11

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills