| name | obsidian-performance-tuning |
| description | 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> |
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
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.(label);
(duration > ) {
.();
} {
.();
}
duration;
}
measure<T>(: , : <T>): <T> {
.(label);
{
();
} {
.(label);
}
}
measureSync<T>(: , : T): T {
.(label);
{
();
} {
.(label);
}
}
}
profiler = (process.. !== );
profiler.(, () => {
.();
});
Step 2: Lazy Initialization
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 .;
}
(): {
. !== ;
}
(): {
. = ;
. = ;
}
}
{
indexService = ( .());
() {
.({
: ,
: ,
: () => {
index = ..();
},
});
}
(): <> {
files = ...();
(files);
}
}
Step 3: Efficient File Processing
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;
}
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..(file., {
content,
: file..,
});
content;
}
processFilesInChunks<T>(
: [],
: <T>,
: {
?: ;
?: ;
?: ;
} = {}
): <T[]> {
{ chunkSize = , pauseMs = , onProgress } = options;
: T[] = [];
( i = ; i < files.; i += chunkSize) {
chunk = files.(i, i + chunkSize);
chunkResults = .(
chunk.( (file))
);
results.(...chunkResults);
onProgress?.(.(i + chunkSize, files.), files.);
(i + chunkSize < files.) {
( (r, pauseMs));
}
}
results;
}
*(
: []
): <{ : ; : }> {
( file files) {
content = ..(file);
{ file, content };
( (r, ));
}
}
(): {
..();
}
(: ): {
..(path);
}
}
Step 4: Memory-Efficient Data Structures
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();
(!file) {
..(path);
;
}
..(file);
}
(: ): {
..(file);
}
}
{
strings = <, >();
(: ): {
existing = ..(str);
(existing) existing;
..(str, str);
str;
}
(): {
..();
}
(): {
..;
}
}
<K, V> {
cache = <K, V>();
: ;
() {
. = maxSize;
}
(: K): V | {
value = ..(key);
(value !== ) {
..(key);
..(key, value);
}
value;
}
(: K, : V): {
(..(key)) {
..(key);
} (.. >= .) {
firstKey = ..().().;
..(firstKey);
}
..(key, value);
}
(): {
..();
}
}
Step 5: Optimize Event Handlers
import { debounce, throttle } from 'lodash-es';
export class OptimizedEventManager {
private plugin: Plugin;
constructor(plugin: Plugin) {
this.plugin = plugin;
}
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);
}
})
);
}
registerThrottledScroll(
element: HTMLElement,
handler: ,
: =
): {
throttledHandler = (handler, wait);
..(element, , throttledHandler);
}
(
: ,
: =
): {
: [] = [];
: . | = ;
..(
....(, {
(file ) {
pendingFiles.(file);
(timeoutId) (timeoutId);
timeoutId = ( {
files = [... (pendingFiles)];
pendingFiles = [];
timeoutId = ;
(files);
}, wait);
}
})
);
}
}
Step 6: UI Rendering Optimization
export class RenderOptimizer {
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);
}
static createVirtualList(
container: HTMLElement,
items: any[],
itemHeight: number,
renderItem: (item: any) => HTMLElement
): void {
const visibleCount = Math.ceil(container.clientHeight / itemHeight) + 2;
let startIndex = ;
= () => {
scrollTop = container.;
newStartIndex = .(scrollTop / itemHeight);
(newStartIndex !== startIndex) {
startIndex = newStartIndex;
container.();
fragment = .();
spacer = .();
spacer.. = ;
fragment.(spacer);
( i = startIndex; i < .(startIndex + visibleCount, items.); i++) {
fragment.((items[i]));
}
bottomSpacer = .();
bottomSpacer.. = ;
fragment.(bottomSpacer);
container.(fragment);
}
};
container.(, render);
();
}
(: ): {
(fn);
}
(: , : <, >): {
( {
.(element., styles);
});
}
}
Output
- Performance profiler for identifying bottlenecks
- Lazy initialization patterns
- Efficient file processing with chunking
- Memory-efficient data structures
- Optimized event handlers
- UI rendering optimizations
Error Handling
| Issue | Cause | Solution |
|---|
| Plugin slow to load | Heavy initialization | Use lazy loading |
| UI freezes | Blocking operations | Use async + chunking |
| Memory growth | Unbounded caching | Use LRU cache |
| Event lag | Unthrottled handlers | Debounce/throttle |
Examples
Memory Usage Monitor
function logMemoryUsage(label: string): void {
if (performance.memory) {
const used = performance.memory.usedJSHeapSize / 1048576;
console.log(`[Memory] ${label}: ${used.toFixed(2)} MB`);
}
}
logMemoryUsage('Before index build');
await buildIndex();
logMemoryUsage('After index build');
Performance Checklist
## Pre-Release Performance Checklist
- [ ] Plugin loads in < 100ms
- [ ] No blocking operations in onload()
- [ ] File operations use cachedRead when possible
- [ ] Event handlers are debounced/throttled
- [ ] Large lists use virtual scrolling
- [ ] Caches have size limits (LRU)
- [ ] Memory doesn't grow unboundedly
- [ ] Works smoothly with 1000+ files
Resources
Next Steps
For resource optimization, see obsidian-cost-tuning.