obsidian-performance-tuning

40
5
Source

Optimize Obsidian plugin performance for smooth operation. Use when experiencing lag, memory issues, or slow startup, or when optimizing plugin code for large vaults. Trigger with phrases like "obsidian performance", "obsidian slow", "optimize obsidian plugin", "obsidian memory usage".

Install

mkdir -p .claude/skills/obsidian-performance-tuning && curl -L -o skill.zip "https://mcp.directory/api/skills/download/1136" && unzip -o skill.zip -d .claude/skills/obsidian-performance-tuning && rm skill.zip

Installs to .claude/skills/obsidian-performance-tuning

About this skill

Obsidian Performance Tuning

Overview

Optimize Obsidian plugin performance for smooth operation in large vaults and resource-constrained environments.

Prerequisites

  • Working Obsidian plugin
  • Developer Tools access (Ctrl/Cmd+Shift+I)
  • Understanding of async JavaScript

Performance Benchmarks

Target Metrics

MetricGoodWarningCritical
Plugin load time< 100ms100-500ms> 500ms
Command execution< 50ms50-200ms> 200ms
File operation< 10ms10-50ms> 50ms
Memory increase< 10MB10-50MB> 50MB
Event handler< 5ms5-20ms> 20ms

Instructions

Step 1: Profile Plugin Performance

// src/utils/profiler.ts
export class PerformanceProfiler {
  private marks: Map<string, number> = new Map();
  private enabled: boolean;

  constructor(enabled: boolean = true) {
    this.enabled = enabled;
  }

  start(label: string): void {
    if (!this.enabled) return;
    this.marks.set(label, performance.now());
  }

  end(label: string): number {
    if (!this.enabled) return 0;

    const start = this.marks.get(label);
    if (!start) return 0;

    const duration = performance.now() - start;
    this.marks.delete(label);

    if (duration > 50) {
      console.warn(`[Performance] ${label}: ${duration.toFixed(2)}ms (slow)`);
    } else {
      console.log(`[Performance] ${label}: ${duration.toFixed(2)}ms`);
    }

    return duration;
  }

  async measure<T>(label: string, fn: () => Promise<T>): Promise<T> {
    this.start(label);
    try {
      return await fn();
    } finally {
      this.end(label);
    }
  }

  measureSync<T>(label: string, fn: () => T): T {
    this.start(label);
    try {
      return fn();
    } finally {
      this.end(label);
    }
  }
}

// Usage:
const profiler = new PerformanceProfiler(process.env.NODE_ENV !== 'production');

await profiler.measure('loadSettings', async () => {
  return this.loadData();
});

Step 2: Lazy Initialization

// src/services/lazy-service.ts
export class LazyService<T> {
  private instance: T | null = null;
  private initializing: Promise<T> | null = null;
  private factory: () => Promise<T>;

  constructor(factory: () => Promise<T>) {
    this.factory = factory;
  }

  async get(): Promise<T> {
    if (this.instance) return this.instance;

    if (this.initializing) return this.initializing;

    this.initializing = this.factory().then(instance => {
      this.instance = instance;
      this.initializing = null;
      return instance;
    });

    return this.initializing;
  }

  isInitialized(): boolean {
    return this.instance !== null;
  }

  clear(): void {
    this.instance = null;
    this.initializing = null;
  }
}

// Usage - defer expensive initialization
export default class MyPlugin extends Plugin {
  private indexService = new LazyService(() => this.buildIndex());

  async onload() {
    // Don't build index immediately
    // Build on first use instead

    this.addCommand({
      id: 'search',
      name: 'Search',
      callback: async () => {
        const index = await this.indexService.get();
        // Use index...
      },
    });
  }

  private async buildIndex(): Promise<SearchIndex> {
    // Expensive operation - only runs when first needed
    const files = this.app.vault.getMarkdownFiles();
    return new SearchIndex(files);
  }
}

Step 3: Efficient File Processing

// src/utils/file-processor.ts
import { TFile, Vault } from 'obsidian';

export class EfficientFileProcessor {
  private vault: Vault;
  private cache: Map<string, { content: string; mtime: number }> = new Map();

  constructor(vault: Vault) {
    this.vault = vault;
  }

  // Use cached read when possible
  async readWithCache(file: TFile): Promise<string> {
    const cached = this.cache.get(file.path);
    if (cached && cached.mtime === file.stat.mtime) {
      return cached.content;
    }

    const content = await this.vault.cachedRead(file);
    this.cache.set(file.path, {
      content,
      mtime: file.stat.mtime,
    });

    return content;
  }

  // Process files in chunks with pauses
  async processFilesInChunks<T>(
    files: TFile[],
    processor: (file: TFile) => Promise<T>,
    options: {
      chunkSize?: number;
      pauseMs?: number;
      onProgress?: (processed: number, total: number) => void;
    } = {}
  ): Promise<T[]> {
    const { chunkSize = 50, pauseMs = 10, onProgress } = options;
    const results: T[] = [];

    for (let i = 0; i < files.length; i += chunkSize) {
      const chunk = files.slice(i, i + chunkSize);

      // Process chunk in parallel
      const chunkResults = await Promise.all(
        chunk.map(file => processor(file))
      );
      results.push(...chunkResults);

      // Report progress
      onProgress?.(Math.min(i + chunkSize, files.length), files.length);

      // Pause to allow UI updates
      if (i + chunkSize < files.length) {
        await new Promise(r => setTimeout(r, pauseMs));
      }
    }

    return results;
  }

  // Generator for memory-efficient iteration
  async *iterateFiles(
    files: TFile[]
  ): AsyncGenerator<{ file: TFile; content: string }> {
    for (const file of files) {
      const content = await this.vault.cachedRead(file);
      yield { file, content };

      // Allow event loop to process
      await new Promise(r => setTimeout(r, 0));
    }
  }

  clearCache(): void {
    this.cache.clear();
  }

  removeFromCache(path: string): void {
    this.cache.delete(path);
  }
}

Step 4: Memory-Efficient Data Structures

// src/utils/efficient-structures.ts

// Use WeakMap for cached data that can be garbage collected
export class WeakFileCache<T> {
  private cache = new WeakMap<object, T>();
  private keyMap = new Map<string, WeakRef<object>>();

  set(path: string, file: object, value: T): void {
    this.cache.set(file, value);
    this.keyMap.set(path, new WeakRef(file));
  }

  get(file: object): T | undefined {
    return this.cache.get(file);
  }

  getByPath(path: string): T | undefined {
    const ref = this.keyMap.get(path);
    if (!ref) return undefined;

    const file = ref.deref();
    if (!file) {
      this.keyMap.delete(path);
      return undefined;
    }

    return this.cache.get(file);
  }

  has(file: object): boolean {
    return this.cache.has(file);
  }
}

// Efficient string storage for repeated values
export class StringInterner {
  private strings = new Map<string, string>();

  intern(str: string): string {
    const existing = this.strings.get(str);
    if (existing) return existing;
    this.strings.set(str, str);
    return str;
  }

  clear(): void {
    this.strings.clear();
  }

  get size(): number {
    return this.strings.size;
  }
}

// LRU cache for bounded memory usage
export class LRUCache<K, V> {
  private cache = new Map<K, V>();
  private maxSize: number;

  constructor(maxSize: number) {
    this.maxSize = maxSize;
  }

  get(key: K): V | undefined {
    const value = this.cache.get(key);
    if (value !== undefined) {
      // Move to end (most recently used)
      this.cache.delete(key);
      this.cache.set(key, value);
    }
    return value;
  }

  set(key: K, value: V): void {
    if (this.cache.has(key)) {
      this.cache.delete(key);
    } else if (this.cache.size >= this.maxSize) {
      // Remove oldest entry
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }
    this.cache.set(key, value);
  }

  clear(): void {
    this.cache.clear();
  }
}

Step 5: Optimize Event Handlers

// src/utils/event-optimizer.ts
import { debounce, throttle } from 'lodash-es';

export class OptimizedEventManager {
  private plugin: Plugin;

  constructor(plugin: Plugin) {
    this.plugin = plugin;
  }

  // Debounced handler for file modifications
  registerDebouncedModify(
    handler: (file: TFile) => void,
    wait: number = 500
  ): void {
    const debouncedHandler = debounce(handler, wait);

    this.plugin.registerEvent(
      this.plugin.app.vault.on('modify', (file) => {
        if (file instanceof TFile) {
          debouncedHandler(file);
        }
      })
    );
  }

  // Throttled handler for frequent events
  registerThrottledScroll(
    element: HTMLElement,
    handler: (event: Event) => void,
    wait: number = 100
  ): void {
    const throttledHandler = throttle(handler, wait);
    this.plugin.registerDomEvent(element, 'scroll', throttledHandler);
  }

  // Batch multiple rapid events
  registerBatchedEvents(
    handler: (files: TFile[]) => void,
    wait: number = 100
  ): void {
    let pendingFiles: TFile[] = [];
    let timeoutId: NodeJS.Timeout | null = null;

    this.plugin.registerEvent(
      this.plugin.app.vault.on('modify', (file) => {
        if (file instanceof TFile) {
          pendingFiles.push(file);

          if (timeoutId) clearTimeout(timeoutId);

          timeoutId = setTimeout(() => {
            const files = [...new Set(pendingFiles)];
            pendingFiles = [];
            timeoutId = null;
            handler(files);
          }, wait);
        }
      })
    );
  }
}

Step 6: UI Rendering Optimization

// src/utils/render-optimizer.ts
export class RenderOptimizer {
  // Use DocumentFragment for batch DOM updates
  static batchRender(
    container: HTMLElement,
    items: string[],
    renderer: (item: string) => HTMLElement
  ): void {
    const fragment = document.createDocumentFragment();

    for (const item of items) {
      fragment.appendChild(renderer(item));
    }

    container.empty();
    container.appendChild(fragment);
  }

  // Virtual scrolling for long lists
  static createVirtualList(
    container: HTMLElement,
    items: any[],
    itemHeight: number,
    renderItem: (item: any) => HTMLElement
  ): void {
    const visibleCount = Math.ceil(container.clientHeight / itemHeight) + 2;
    let startIndex = 0;

    cons

---

*Content truncated.*

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

10435

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

8233

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

17728

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

5317

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

12414

optimizing-sql-queries

jeremylongshore

This skill analyzes and optimizes SQL queries for improved performance. It identifies potential bottlenecks, suggests optimal indexes, and proposes query rewrites. Use this when the user mentions "optimize SQL query", "improve SQL performance", "SQL query optimization", "slow SQL query", or asks for help with "SQL indexing". The skill helps enhance database efficiency by analyzing query structure, recommending indexes, and reviewing execution plans.

5413

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,5671,368

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

1,1141,185

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,4151,108

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

1,192746

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

1,149683

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,306610

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.