Idiomark V2 Performance & Benchmarks
Version: 1.0.0 | Last Updated: 2026-02-11 | Status: Active
Executive Summary
This document defines performance expectations, benchmarks, and optimization strategies for Idiomark V2 features. V2 adds psycholinguistic analysis which has measurable computational overhead.
Key Principle: V2 should not significantly impact user experience. Performance budgets ensure V2 remains practical.
Performance Budgets
Extraction Performance
| Operation | V1 Baseline | V1 + V2 | Overhead | Budget |
|---|---|---|---|---|
| Small extraction (500 words) | ~3s | ~3.2s | +200ms | < 500ms |
| Medium extraction (2,000 words) | ~8s | ~8.5s | +500ms | < 1s |
| Large extraction (10,000 words) | ~35s | ~37s | +2s | < 5s |
Memory Usage
| Operation | V1 Baseline | V1 + V2 | Overhead | Budget |
|---|---|---|---|---|
| Extraction (idle) | ~50MB | ~60MB | +10MB | < 50MB |
| Extraction (peak) | ~150MB | ~180MB | +30MB | < 100MB |
| Reader (loaded) | ~5MB | ~8MB | +3MB | < 10MB |
Prompt Building
| Operation | V1 Baseline | V1 + V2 | Overhead | Budget |
|---|---|---|---|---|
| Build prompt | < 1ms | < 5ms | +4ms | < 10ms |
| Prompt size | ~800 tokens | ~1200 tokens | +400 tokens | < 500 tokens |
Component Benchmarks
1. Linguistic Marker Analysis
Since this is rule-based (no LLM), it should be very fast:
Test: Analyze 10,000 words for linguistic markers
Target:
- Duration: < 50ms
- Memory: < 5MB
- Accuracy: > 95%
Implementation:
- Regex-based pattern matching
- Single-pass text analysis
- Pre-compiled word lists
Benchmark Results (Target):
| Input Size | Duration | Memory | Throughput |
|---|---|---|---|
| 100 words | < 1ms | < 1MB | > 100k words/sec |
| 1,000 words | < 5ms | < 2MB | > 200k words/sec |
| 10,000 words | < 50ms | < 5MB | > 200k words/sec |
2. Big Five Extraction (LLM-based)
Test: Extract OCEAN scores from text samples
Target:
- Small (500 words): < 3s total
- Medium (2,000 words): < 8s total
- Large (10,000 words): < 35s total
Breakdown:
- Text preprocessing: ~5% of time
- LLM API call: ~90% of time
- Response parsing: ~5% of time
Optimization Strategies:
// 1. Batch processing for large texts
async function extractBigFiveLargeText(text: string) {
const chunks = splitIntoChunks(text, 2000) // 2000 words per chunk
// Extract from each chunk in parallel
const chunkResults = await Promise.all(
chunks.map(chunk => llmCall(BIG_FIVE_PROMPT, chunk))
)
// Aggregate results
return aggregateBigFiveScores(chunkResults)
}
// 2. Cache common patterns
const bigFiveCache = new LRUCache<string, BigFivePersonality>({
max: 1000,
ttl: 1000 * 60 * 60 // 1 hour
})
async function extractBigFiveCached(text: string) {
const hash = hashText(text)
if (bigFiveCache.has(hash)) {
return bigFiveCache.get(hash)
}
const result = await extractBigFive(text)
bigFiveCache.set(hash, result)
return result
}
3. Communication Style Extraction (LLM-based)
Similar to Big Five, but may require fewer samples:
Target:
- Small (500 words): < 2s
- Medium (2,000 words): < 5s
- Large (10,000 words): < 20s
Optimization:
- Can be inferred from smaller sample size
- Cacheable patterns
- Less context required than Big Five
Prompt Size Optimization
V2 prompts add significant token overhead. Strategies to minimize:
1. Template Optimization
Before (Unoptimized):
{{ Big Five explanation (200 tokens) }}
{{ Communication Style explanation (150 tokens) }}
{{ Linguistic Markers explanation (150 tokens) }}
{{ Cognitive Patterns explanation (150 tokens) }}
{{ Emotional Patterns explanation (150 tokens) }}
{{ Social Dynamics explanation (150 tokens) }}
Total: ~950 tokens overhead
After (Optimized):
{{ Condensed V2 framework (200 tokens) }}
{{ Only present dimensions (varies) }}
Total: ~200-500 tokens overhead
2. Selective Dimension Loading
interface PromptOptions {
includeV2?: boolean
v2Dimensions?: Array<keyof PersonalityV2>
}
function buildPrompt(
personality: Personality,
personalityV2: PersonalityV2 | undefined,
options: PromptOptions
): string {
let prompt = buildV1Prompt(personality)
if (options.includeV2 && personalityV2) {
const dimensions = options.v2Dimensions || Object.keys(personalityV2)
for (const dim of dimensions) {
if (personalityV2[dim]) {
prompt += buildDimensionPrompt(dim, personalityV2[dim])
}
}
}
return prompt
}
// Usage: Only include dimensions that matter
const prompt = buildPrompt(
personality,
personality_v2,
{
includeV2: true,
v2Dimensions: ['big_five', 'communication_style'] // Skip others
}
)
3. Lazy Prompt Building
class CachedPromptBuilder {
private cache = new Map<string, string>()
build(idiomarkFile: IdiomarkFileV2, message: string): string {
const cacheKey = this.getCacheKey(idiomarkFile)
// Reuse cached personality section
let personalitySection = this.cache.get(cacheKey)
if (!personalitySection) {
personalitySection = this.buildPersonalitySection(idiomarkFile)
this.cache.set(cacheKey, personalitySection)
}
// Only rebuild message-specific part
return `${personalitySection}\n\nUser: ${message}\nResponse:`
}
private getCacheKey(file: IdiomarkFileV2): string {
// Hash of personality_v2 structure
return JSON.stringify(file.personality_v2)
}
}
LLM API Optimization
Provider Selection
| Provider | Speed | Quality | Cost | Recommendation |
|---|---|---|---|---|
| Anthropic Claude | Fast | High | Medium | Primary |
| OpenAI GPT-4 | Medium | High | High | Secondary |
| OpenAI GPT-3.5 | Fast | Medium | Low | Testing |
| Local Llama | Variable | Medium | Low | Experimental |
Parallel Extraction
// Extract all V2 dimensions in parallel
async function extractV2Parallel(text: string): Promise<PersonalityV2> {
const [
bigFive,
linguisticMarkers, // No LLM needed
communicationStyle,
cognitivePatterns,
emotionalPatterns,
socialDynamics
] = await Promise.all([
extractBigFive(text),
extractLinguisticMarkers(text), // Fast, local
extractCommunicationStyle(text),
extractCognitivePatterns(text),
extractEmotionalPatterns(text),
extractSocialDynamics(text)
])
return {
big_five: bigFive,
linguistic_markers: linguisticMarkers,
communication_style: communicationStyle,
cognitive_patterns: cognitivePatterns,
emotional_patterns: emotionalPatterns,
social_dynamics: socialDynamics
}
}
Speedup: Parallel extraction reduces total time by ~50% compared to sequential.
Batching for Multiple Users
// Batch multiple extractions in single API call
async function batchExtractBigFive(
userTexts: Array<{ userId: string, text: string }>
): Promise<Map<string, BigFivePersonality>> {
const prompt = `
Extract Big Five personality for each user below:
${userTexts.map((u, i) => `
User ${i + 1} (ID: ${u.userId}):
${u.text.substring(0, 500)}...
`).join('\n')}
Output JSON mapping user IDs to OCEAN scores:
{
"user_id_1": { "openness": 0.5, ... },
"user_id_2": { "openness": 0.7, ... }
}
`.trim()
const response = await llmCall(prompt)
return new Map(Object.entries(response))
}
Benefits:
- Single API call for multiple users
- Reduced latency through batching
- Lower cost per user
Monitoring & Alerting
Metrics to Track
// packages/core/src/monitoring/performance.ts
export interface PerformanceMetrics {
extraction: {
duration_v1: number
duration_v2: number
overhead_ms: number
overhead_percent: number
}
prompt: {
build_duration_ms: number
v1_token_count: number
v2_token_count: number
token_overhead: number
}
memory: {
heap_used_mb: number
heap_total_mb: number
external_mb: number
}
api: {
llm_calls_count: number
llm_duration_total_ms: number
llm_duration_avg_ms: number
cache_hit_rate: number
}
}
export function recordExtractionMetrics(
v1Duration: number,
v2Duration: number,
result: AnalysisResult
): void {
const metrics: PerformanceMetrics = {
extraction: {
duration_v1: v1Duration,
duration_v2: v2Duration,
overhead_ms: v2Duration - v1Duration,
overhead_percent: ((v2Duration - v1Duration) / v1Duration) * 100
},
// ...
}
// Send to monitoring service
monitor.track('idiomark.extraction', metrics)
}
Alert Thresholds
| Metric | Warning | Critical | Action |
|---|---|---|---|
| V2 overhead | > 500ms | > 2000ms | Investigate bottlenecks |
| Memory overhead | > 50MB | > 100MB | Check for leaks |
| Prompt size | > 1500 tokens | > 2500 tokens | Optimize templates |
| LLM failures | > 5% | > 10% | Check API status |
| Cache hit rate | < 20% | < 10% | Review cache strategy |
Performance Testing
Benchmark Suite
// tests/performance/benchmark.ts
import { performance } from 'perf_hooks'
export class PerformanceBenchmark {
async benchmarkExtraction(
sampleTexts: Array<{ size: number, text: string }>
): Promise<BenchmarkResults> {
const results = []
for (const sample of sampleTexts) {
// Warmup
await this.runExtraction(sample.text, { enableV2: false })
// V1 baseline
const v1Start = performance.now()
await this.runExtraction(sample.text, { enableV2: false })
const v1Duration = performance.now() - v1Start
// V2 extraction
const v2Start = performance.now()
await this.runExtraction(sample.text, { enableV2: true })
const v2Duration = performance.now() - v2Start
results.push({
wordCount: sample.size,
v1Duration,
v2Duration,
overhead: v2Duration - v1Duration,
overheadPercent: ((v2Duration - v1Duration) / v1Duration) * 100
})
}
return results
}
async benchmarkPromptBuilding(
iterations: number = 1000
): Promise<PromptBenchmarkResults> {
const idiomarkFile = await loadTestFile()
const start = performance.now()
for (let i = 0; i < iterations; i++) {
buildResponsePromptFromIdiomarkFile(idiomarkFile, 'test message')
}
const duration = performance.now() - start
return {
totalDuration: duration,
avgDuration: duration / iterations,
operationsPerSecond: iterations / (duration / 1000)
}
}
}
Load Testing
# Run performance benchmarks
pnpm test:performance
# Expected output:
#
# Extraction Performance:
# 500 words: V1=2.8s, V2=3.0s, overhead=200ms (7%)
# 2000 words: V1=7.5s, V2=8.0s, overhead=500ms (6%)
# 10000 words: V1=34s, V2=36s, overhead=2000ms (5%)
#
# Prompt Building:
# V1: 0.5ms avg, 2000 ops/sec
# V2: 3ms avg, 333 ops/sec
#
# Memory Usage:
# Base: 50MB
# V2 overhead: +10MB (20%)
Optimization Roadmap
Phase 1: Immediate (Week 1-2)
- Implement parallel V2 extraction
- Add prompt caching
- Optimize linguistic marker regex patterns
- Add performance monitoring
Phase 2: Short-term (Month 1)
- Implement selective dimension loading
- Add result caching layer
- Optimize prompt templates
- Implement batch extraction
Phase 3: Medium-term (Month 2-3)
- Implement streaming extraction
- Add incremental V2 updates
- Implement differential extraction (only changed dimensions)
- Explore local LLM options
Phase 4: Long-term (Month 4+)
- Implement pre-trained models for V2 dimensions
- Add edge computing support
- Implement distributed extraction
- Optimize for specific LLM providers
Performance vs Quality Trade-offs
Conservative Mode (Fast)
const analyzer = new PersonalityAnalyzer({
enableV2: true,
mode: 'conservative', // Fast, lower quality
v2Options: {
dimensions: ['big_five', 'linguistic_markers'], // Only fastest
sampleSize: 500, // Smaller samples
parallel: false // Sequential for stability
}
})
// Expected: < 5s for 2000 words
// Quality: Good for basic personality
Balanced Mode (Default)
const analyzer = new PersonalityAnalyzer({
enableV2: true,
mode: 'balanced', // Default
v2Options: {
dimensions: ['big_five', 'linguistic_markers', 'communication_style'],
sampleSize: 2000,
parallel: true
}
})
// Expected: ~8s for 2000 words
// Quality: Good for most use cases
Thorough Mode (High Quality)
const analyzer = new PersonalityAnalyzer({
enableV2: true,
mode: 'thorough', // Slow, highest quality
v2Options: {
dimensions: 'all', // All 6 dimensions
sampleSize: 5000,
parallel: true,
retries: 3,
aggregate: true // Multiple extractions, aggregate results
}
})
// Expected: ~20s for 5000 words
// Quality: Research-grade personality profile
Summary
| Aspect | Target | Status |
|---|---|---|
| Extraction overhead | < 15% | ⬜ To be verified |
| Memory overhead | < 50MB | ⬜ To be verified |
| Prompt token overhead | < 500 | ⬜ To be verified |
| Linguistic marker speed | < 50ms for 10k words | ⬜ To be verified |
| Cache hit rate | > 30% | ⬜ To be verified |
Next Steps:
- Implement performance monitoring
- Run benchmark suite
- Identify bottlenecks
- Optimize hot paths
- Document actual vs. expected performance
Document Owner: Idiomark Performance Team Review Cadence: Weekly Last Updated: 2026-02-11