obsidian-performance-tuning
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". allowed-tools: Read, Write, Edit version: 1.0.0 license: MIT author: Jeremy Longshore <jeremy@intentsolutions.io>
Allowed Tools
No tools specified
Provided by Plugin
obsidian-pack
Claude Code skill pack for Obsidian plugin development and vault management (24 skills)
Installation
This skill is included in the obsidian-pack plugin:
/plugin install obsidian-pack@claude-code-plugins-plus
Click to copy
Instructions
# 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
| Metric | Good | Warning | Critical |
|--------|------|---------|----------|
| Plugin load time | < 100ms | 100-500ms | > 500ms |
| Command execution | < 50ms | 50-200ms | > 200ms |
| File operation | < 10ms | 10-50ms | > 50ms |
| Memory increase | < 10MB | 10-50MB | > 50MB |
| Event handler | < 5ms | 5-20ms | > 20ms |
## Instructions
### Step 1: Profile Plugin Performance
```typescript
// src/utils/profiler.ts
export class PerformanceProfiler {
private marks: Map = 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(label: string, fn: () => Promise): Promise {
this.start(label);
try {
return await fn();
} finally {
this.end(label);
}
}
measureSync(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
```typescript
// src/services/lazy-service.ts
export class LazyService {
private instance: T | null = null;
private initializing: Promise | null = null;
private factory: () => Promise;
constructor(factory: () => Promise) {
this.factory = factory;
}
async get(): Promise {
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 {
// Expensive operation - only runs when first needed
const files = this.app.vault.getMarkdownFiles();
return new SearchIndex(files);
}
}
```
### Step 3: Efficient File Processing
```typescript
// src/utils/file-processor.ts
import { TFile, Vault } from 'obsidian';
export class EfficientFileProcessor {
private vault: Vault;
private cache: Map = new Map();
constructor(vault: Vault) {
this.vault = vault;
}
// Use cached read when possible
async readWithCache(file: TFile): Promise {
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(
files: TFile[],
processor: (file: TFile) => Promise,
options: {
chunkSize?: number;
pauseMs?: number;
onProgress?: (processed: number, total: number) => void;
} = {}
): Promise {
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
```typescript
// src/utils/efficient-structures.ts
// Use WeakMap for cached data that can be garbage collected
export class WeakFileCache {
private cache = new WeakMap