跳到正文
cccskills
免费在 GitHub 公开

performance-tuner

Performance optimization, profiling, caching strategies, lazy loading, bundle optimization, and monitoring. Use when optimizing application performance, reducing bundle size, implementing caching, or analyzing bottlenecks.

中文简介正在准备中。当前显示原文说明。

集成工具Redis
查看安装方法

包含的文件(1)

  • SKILL.md5.4 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Performance Tuner

Caching Strategies

Redis Caching

import { Redis } from 'ioredis';

export class CacheManager {
  private redis = new Redis(process.env.REDIS_URL);
  
  async get<T>(key: string): Promise<T | null> {
    const data = await this.redis.get(key);
    return data ? JSON.parse(data) : null;
  }
  
  async set<T>(key: string, value: T, ttl: number): Promise<void> {
    await this.redis.setex(key, ttl, JSON.stringify(value));
  }
  
  async getOrSet<T>(
    key: string,
    factory: () => Promise<T>,
    ttl: number
  ): Promise<T> {
    const cached = await this.get<T>(key);
    if (cached) return cached;
    
    const value = await factory();
    await this.set(key, value, ttl);
    return value;
  }
}

// Usage with stale-while-revalidate
export class SWRCache {
  async get<T>(key: string): Promise<T> {
    const [fresh, stale] = await Promise.all([
      this.redis.get(`fresh:${key}`),
      this.redis.get(`stale:${key}`)
    ]);
    
    if (fresh) return JSON.parse(fresh);
    
    // Trigger revalidation in background
    if (stale) {
      this.revalidate(key);
      return JSON.parse(stale);
    }
    
    return this.fetchAndCache(key);
  }
}

HTTP Caching Headers

export function setCacheHeaders(
  res: Response,
  options: CacheOptions
) {
  if (options.swr) {
    res.setHeader('Cache-Control', 
      `public, s-maxage=${options.stale}, stale-while-revalidate=${options.revalidate}`
    );
  } else if (options.immutable) {
    res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
  } else {
    res.setHeader('Cache-Control', `public, max-age=${options.maxAge}`);
  }
}

Bundle Optimization

Dynamic Imports

// Lazy load heavy components
const HeavyChart = dynamic(() => import('./HeavyChart'), {
  loading: () => <ChartSkeleton />,
  ssr: false // Disable SSR for browser-only libraries
});

// Preload on hover
function LinkWithPreload({ href, children }) {
  return (
    <Link 
      href={href}
      onMouseEnter={() => {
        const Component = dynamic(() => import(`./pages${href}`));
      }}
    >
      {children}
    </Link>
  );
}

Tree Shaking

// ✅ Good: Named imports
import { map, filter } from 'lodash-es';

// ❌ Bad: Full import
import _ from 'lodash';

// ✅ Good: Barrel exports with care
export { Button } from './Button';
export { Input } from './Input';

Database Query Optimization

Query Analysis

// Explain query plans
const explain = await db.execute(sql`
  EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
  SELECT * FROM users WHERE email = ${email}
`);

// Index usage check
const indexUsage = await db.execute(sql`
  SELECT 
    schemaname,
    tablename,
    attname as column,
    n_tup_read,
    n_tup_fetch
  FROM pg_stats
  WHERE tablename = 'users'
`);

Connection Pooling

import { Pool } from 'pg';

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 20,                    // Maximum pool size
  idleTimeoutMillis: 30000,   // Close idle connections
  connectionTimeoutMillis: 2000,
  application_name: 'trinity_app'
});

// Monitor pool
pool.on('connect', () => console.log('New client connected'));
pool.on('error', (err) => console.error('Pool error:', err));

Image Optimization

Next.js Image

import Image from 'next/image';

<Image
  src="/hero.jpg"
  alt="Hero"
  width={1200}
  height={600}
  priority // Above-the-fold images
  placeholder="blur"
  blurDataURL="data:image/jpeg;base64,..."
/>

Responsive Images

<Image
  src="/photo.jpg"
  alt="Photo"
  sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
  fill
  className="object-cover"
/>

Performance Monitoring

Web Vitals

import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';

function sendToAnalytics(metric) {
  const body = JSON.stringify(metric);
  (navigator.sendBeacon && navigator.sendBeacon('/analytics', body)) ||
    fetch('/analytics', { body, method: 'POST', keepalive: true });
}

getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getFCP(sendToAnalytics);
getLCP(sendToAnalytics);
getTTFB(sendToAnalytics);

Custom Metrics

export class PerformanceMonitor {
  measure(name: string, fn: () => Promise<T>): Promise<T> {
    const start = performance.now();
    
    return fn().finally(() => {
      const duration = performance.now() - start;
      
      // Send to monitoring
      this.report({
        name: `timing.${name}`,
        value: duration,
        unit: 'ms'
      });
    });
  }
}

Memory Management

WeakRef for Caching

class WeakCache<K, V extends object> {
  private cache = new Map<K, WeakRef<V>>();
  private finalizer = new FinalizationRegistry<K>(key => {
    this.cache.delete(key);
  });
  
  set(key: K, value: V) {
    this.cache.set(key, new WeakRef(value));
    this.finalizer.register(value, key);
  }
  
  get(key: K): V | undefined {
    const ref = this.cache.get(key);
    return ref?.deref();
  }
}

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

ai-sdk

免费

Vercel AI SDK expert guidance. Use when building AI-powered features — chat interfaces, text generation, structured output, tool calling, agents, MCP integration, streaming, embeddings, reranking, image generation, or working with any LLM provider.

中文简介正在准备中。当前显示原文说明。

garochee33/DSH42026年10月19日 更新

Algorithm design and analysis skill for DSH; use when working on optimization, data structures, or computational procedures.

中文简介正在准备中。当前显示原文说明。

garochee33/DSH42026年10月19日 更新

Design and implement scalable API gateways, RESTful APIs, GraphQL endpoints, WebSocket handlers, and microservice communication patterns. Use when creating API routes, designing endpoints, implementing middleware, or setting up service mesh architectures.

中文简介正在准备中。当前显示原文说明。

garochee33/DSH42026年10月19日 更新

best-of-n

免费

Implement a task N ways in parallel and pick the best. Spawns multiple subagents in isolated worktrees, evaluates all candidates, and applies the winner. Use when asked to "best of n", "try multiple approaches", "parallel implementations", "/best-of-n", or "/bon".

中文简介正在准备中。当前显示原文说明。

garochee33/DSH42026年10月19日 更新

check

免费

Check your work with a verification subagent. Spawns a verifier that reviews diffs, runs builds and tests, and evaluates correctness. Use when asked to "check work", "verify changes", "self-verify", "/check", "/verify", "/check-work", or "/self-verify".

中文简介正在准备中。当前显示原文说明。

garochee33/DSH42026年10月19日 更新

CI/CD pipeline design, GitHub Actions workflows, deployment automation, infrastructure as code, and release management. Use when setting up CI/CD, automating deployments, configuring build pipelines, or managing releases.

中文简介正在准备中。当前显示原文说明。

garochee33/DSH42026年10月19日 更新

查看 garochee33 的全部技能

报告此技能的问题