Runtime Hot-Path Optimization
Learn about the high-performance runtime optimization system introduced in WeaveDI v3.1.0.
Overview
Runtime hot-path optimization is an advanced optimization system designed to eliminate performance bottlenecks in dependency injection.
Core Optimization Techniques
TypeID + Index Access
ObjectIdentifier→Intslot mapping- O(1) array index access instead of dictionary lookup
- Memory access pattern optimization
Snapshot/Lock-Free Reads
- Immutable Storage class-based snapshot approach
- Complete elimination of read contention
- Locking only during writes
Inline Optimization
- Applied
@inlinable+@inline(__always) - Cross-module optimization with
@_alwaysEmitIntoClient - Reduced function call overhead
- Applied
Factory Chain Elimination
- Direct call paths without intermediate factory steps
- Dependency chain flattening
- Removal of multi-stage factory costs
Scope-Specific Static Storage
- Separation of singleton/session/request scopes
- Atomic once initialization
- Race condition elimination
Usage
Automatic Optimization
UnifiedRegistry optimization is automatically enabled in WeaveDI v3.2.0+. No configuration required:
swift
import WeaveDI
// ✅ Optimizations are automatically applied
let service = UnifiedDI.resolve(UserService.self)
// ✅ DIContainer also benefits from UnifiedRegistry optimization
let container = WeaveDI.Container()
let service2 = container.resolve(UserService.self)Performance Verification
swift
// Check optimization status
let isOptimized = await UnifiedRegistry.shared.isOptimizationEnabled
print("Optimization enabled: \(isOptimized)")
// Disable optimization
await UnifiedRegistry.shared.disableOptimization()Performance Improvements
| Scenario | Improvement | Description |
|---|---|---|
| Single-threaded resolve | 50-80% faster | TypeID + direct access |
| Multi-threaded reads | 2-3x throughput | Lock-free snapshots |
| Complex dependencies | 20-40% faster | Chain flattening |
Benchmarks
Run the included benchmarks to measure performance improvements:
bash
swift run -c release Benchmarks --count 100k --quickCompatibility
- 100% API compatibility: No changes to existing code
- Opt-in optimization: Enable/disable anytime
- Gradual migration: Phased adoption support
- Zero breaking changes: Complete preservation of existing behavior
Internal Implementation
Optimizations are implemented in the following files:
OptimizedTypeRegistry.swift- TypeID systemAtomicStorage.swift- Lock-free storageDirectCallRegistry.swift- Direct call pathsOptimizedScopeStorage.swift- Scope optimization