OB

obsidian-performance-tuning

Guides optimization of Obsidian plugins to ensure responsiveness in vaults with thousands of files.

Install

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

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

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Optimize Obsidian plugin performance for smooth operation in large vaults.
74 charsno explicit “when” trigger
Advanced

Key capabilities

  • Profile plugin load times and command execution using DevTools.
  • Implement lazy initialization to defer expensive work until needed.
  • Process large numbers of files in batches to prevent UI freezes.
  • Manage memory usage with LRU caches for bounded memory.
  • Debounce event handlers to reduce unnecessary processing.
  • Optimize DOM rendering using DocumentFragment and requestAnimationFrame.

How it works

The skill guides through profiling plugin code with DevTools and applying specific JavaScript patterns like lazy initialization, batch processing, and event debouncing to improve performance.

Inputs & outputs

You give it
Obsidian plugin code and performance metrics from DevTools.
You get back
Optimized plugin code with improved load times, reduced memory, and smoother UI.

When to use obsidian-performance-tuning

  • Optimize plugin load times
  • Reduce memory usage of Obsidian plugins
  • Profile bottlenecks in plugin code
  • Implement debouncing for file operations

About this skill

Obsidian Performance Tuning

Overview

Optimize Obsidian plugin performance for large vaults (10,000+ files): profile bottlenecks with DevTools, implement lazy initialization, process files in batches with UI yielding, use LRU caches with bounded memory, debounce event handlers, and optimize DOM rendering with virtual scrolling and DocumentFragment.

Prerequisites

  • Working Obsidian plugin with at least one performance concern
  • Developer Console access (Ctrl+Shift+I / Cmd+Option+I)
  • Understanding of async JavaScript and the event loop

Performance Benchmarks

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

Instructions

Step 1: Profile with DevTools Performance Tab

// Add timing instrumentation to identify bottlenecks
export default class MyPlugin extends Plugin {
  async onload() {
    const loadStart = performance.now();

    await this.loadSettings();
    console.log(`[perf] loadSettings: ${(performance.now() - loadStart).toFixed(1)}ms`);

    const indexStart = performance.now();
    await this.buildIndex();
    console.log(`[perf] buildIndex: ${(performance.now() - indexStart).toFixed(1)}ms`);

    const cmdStart = performance.now();
    this.registerCommands();
    console.log(`[perf] registerCommands: ${(performance.now() - cmdStart).toFixed(1)}ms`);

    console.log(`[perf] total onload: ${(performance.now() - loadStart).toFixed(1)}ms`);
  }
}

For deeper analysis, use the DevTools Performance tab:

  1. Open DevTools (Ctrl+Shift+I)
  2. Go to Performance tab
  3. Click Record
  4. Toggle your plugin off/on in Settings > Community Plugins
  5. Stop recording
  6. Look for long tasks (yellow bars > 50ms) in the flame chart

Step 2: Lazy Initialization — Defer Expensive Work

// BAD: build index on load (blocks startup)
async onload() {
  this.index = await this.buildFullIndex(); // 2 seconds on large vaults
}

// GOOD: lazy — build on first use
export default class MyPlugin extends Plugin {
  private _index: Map<string, string[]> | null = null;
  private indexPromise: Promise<Map<string, string[]>> | null = null;

  async getIndex(): Promise<Map<string, string[]>> {
    if (this._index) return this._index;
    if (!this.indexPromise) {
      this.indexPromise = this.buildFullIndex().then(idx => {
        this._index = idx;
        this.indexPromise = null;
        return idx;
      });
    }
    return this.indexPromise;
  }

  async onload() {
    // Register commands immediately — index builds on first command use
    this.addCommand({
      id: 'search',
      name: 'Search indexed notes',
      callback: async () => {
        const index = await this.getIndex(); // builds on first call only
        // ... use index
      },
    });
  }

  private async buildFullIndex(): Promise<Map<string, string[]>> {
    const index = new Map<string, string[]>();
    const files = this.app.vault.getMarkdownFiles();
    for (const file of files) {
      const cache = this.app.metadataCache.getFileCache(file);
      if (cache?.tags) {
        index.set(file.path, cache.tags.map(t => t.tag));
      }
    }
    return index;
  }
}

Step 3: Batch File Processing with UI Yielding

import { TFile, Notice } from 'obsidian';

async processAllFiles(statusEl?: HTMLElement): Promise<number> {
  const files = this.app.vault.getMarkdownFiles();
  const BATCH_SIZE = 50;
  let processed = 0;

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

    for (const file of batch) {
      // Use cachedRead — avoids hitting disk on every call
      const content = await this.app.vault.cachedRead(file);
      this.processContent(file, content);
      processed++;
    }

    // Yield to UI thread — prevents "not responding" dialog
    await sleep(0);

    // Update progress
    if (statusEl) {
      const pct = Math.round((processed / files.length) * 100);
      statusEl.setText(`Processing: ${pct}% (${processed}/${files.length})`);
    }
  }

  return processed;
}

// Helper: Obsidian exports sleep(), or use this
function sleep(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

Step 4: LRU Cache for Bounded Memory

// src/services/lru-cache.ts
export class LRUCache<K, V> {
  private cache = new Map<K, V>();

  constructor(private maxSize: number) {}

  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) {
    this.cache.delete(key); // remove if exists (reinserts at end)
    this.cache.set(key, value);
    if (this.cache.size > this.maxSize) {
      // Evict oldest (first) entry
      const oldest = this.cache.keys().next().value;
      if (oldest !== undefined) this.cache.delete(oldest);
    }
  }

  has(key: K): boolean { return this.cache.has(key); }
  delete(key: K): boolean { return this.cache.delete(key); }
  clear() { this.cache.clear(); }
  get size(): number { return this.cache.size; }
}

// Usage: cache processed file results by mtime
class FileProcessor {
  private cache = new LRUCache<string, { mtime: number; result: string }>(500);

  async process(file: TFile): Promise<string> {
    const cached = this.cache.get(file.path);
    if (cached && cached.mtime === file.stat.mtime) {
      return cached.result; // cache hit — skip expensive processing
    }

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

Step 5: Debounce and Throttle Event Handlers

import { Plugin, TFile, debounce } from 'obsidian';

export default class MyPlugin extends Plugin {
  // Global debounce: runs 500ms after last modify event
  private handleModify = debounce(
    (file: TFile) => {
      const cache = this.app.metadataCache.getFileCache(file);
      if (cache?.frontmatter?.tracked) {
        this.reindexFile(file);
      }
    },
    500,
    true // trailing edge
  );

  // Per-file debounce: separate timer for each file
  private fileTimers = new Map<string, ReturnType<typeof setTimeout>>();

  private debouncedPerFile(file: TFile, fn: () => void, delay = 1000) {
    const existing = this.fileTimers.get(file.path);
    if (existing) clearTimeout(existing);
    this.fileTimers.set(file.path, setTimeout(() => {
      this.fileTimers.delete(file.path);
      fn();
    }, delay));
  }

  async onload() {
    this.registerEvent(
      this.app.vault.on('modify', (file) => {
        if (file instanceof TFile && file.extension === 'md') {
          this.handleModify(file);
        }
      })
    );
  }

  onunload() {
    for (const timer of this.fileTimers.values()) clearTimeout(timer);
    this.fileTimers.clear();
  }
}

Step 6: Optimize DOM Rendering

// BAD: updating DOM on every event
this.registerEvent(this.app.vault.on('modify', () => {
  this.containerEl.empty();
  this.renderFullList(); // re-renders 1000 items on every keystroke
}));

// GOOD: DocumentFragment for batch DOM updates
private renderFileList(container: HTMLElement, files: TFile[]) {
  const fragment = document.createDocumentFragment();
  for (const file of files) {
    const el = document.createElement('div');
    el.className = 'file-item';
    el.textContent = file.basename;
    el.addEventListener('click', () => {
      this.app.workspace.getLeaf().openFile(file);
    });
    fragment.appendChild(el);
  }
  container.empty();
  container.appendChild(fragment);
}

// GOOD: requestAnimationFrame for coalesced updates
private pendingRender = false;

private scheduleRender() {
  if (!this.pendingRender) {
    this.pendingRender = true;
    requestAnimationFrame(() => {
      this.render();
      this.pendingRender = false;
    });
  }
}

// GOOD: Virtual scrolling for long lists
private renderVirtualList(container: HTMLElement, items: string[], itemHeight = 24) {
  const visibleCount = Math.ceil(container.clientHeight / itemHeight);
  let scrollTop = 0;

  const content = container.createEl('div', {
    attr: { style: `height: ${items.length * itemHeight}px; position: relative;` },
  });

  const renderVisible = () => {
    const start = Math.floor(scrollTop / itemHeight);
    const end = Math.min(start + visibleCount + 5, items.length);

    content.empty();
    for (let i = start; i < end; i++) {
      content.createEl('div', {
        text: items[i],
        attr: { style: `position: absolute; top: ${i * itemHeight}px; height: ${itemHeight}px;` },
      });
    }
  };

  container.addEventListener('scroll', () => {
    scrollTop = container.scrollTop;
    requestAnimationFrame(renderVisible);
  });

  renderVisible();
}

Step 7: Memory Leak Prevention

// Common leak: WeakRef/WeakMap for file references
// Files can be deleted — holding TFile references prevents GC
private fileData = new WeakMap<TFile, ProcessedData>();

// Common leak: unregistered event listeners
// BAD:
document.addEventListener('click', this.handler); // leaks on unload

// GOOD:
this.registerDomEvent(document, 'click', this.handler); // auto-cleaned

// Common leak: uncleaned intervals
// BAD:
setInterval(() => this.sync(), 60000); // runs forever after unload

// GOOD:
this.registerInterval(window.setInterval(() => this.sync(), 60000)); // auto-cleaned

// Audit: check memory in DevTools
// Console > Performance.memory.usedJSHeapSize
// Enable/disable your plugin, check if memory drops back to baseline
``

---

*Content truncated.*

When not to use it

  • When `cachedRead` returns stale data and freshness is critical.
  • When the plugin does not release memory on disable due to missing cleanup.
  • When `onload` completes in less than 100ms and no synchronous loops are present.

Prerequisites

Working Obsidian plugin with at least one performance concernDeveloper Console access (Ctrl+Shift+I / Cmd+Option+I)Understanding of async JavaScript and the event loop

Limitations

  • Cannot guarantee data freshness when using `cachedRead`.
  • Cannot automatically clean up memory if `registerEvent`/`registerInterval` methods are not used.
  • Does not support raw `addEventListener` or `setInterval` for cleanup.

How it compares

This skill provides concrete code examples and benchmarks for optimizing Obsidian plugin performance, unlike general programming advice which may not address Obsidian's specific API and environment.

Compared to similar skills

obsidian-performance-tuning side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
obsidian-performance-tuning (this skill)625dReviewAdvanced
obsidian-observability525dReviewIntermediate
obsidian-rate-limits525dNo flagsIntermediate
codex-code-review17moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

Search skills

Search the agent skills registry