How This Benchmark Works
- Wire Test: Uses manually written code to simulate Wire's behavior (since Wire generates Go code at compile time).
- Dig Test: Uses Uber's Dig to inject dependencies dynamically at runtime.
- Manual DI Test: A baseline to compare against both approaches.
The benchmark runs each method multiple times to measure execution speed.
Install Dependencies
First, install Wire and Dig:
go install github.com/google/wire/cmd/wire@latest
go get go.uber.org/dig
Create the Benchmark File
Create a new file benchmark_test.go:
package main
import (
"testing"
"go.uber.org/dig"
"github.com/google/wire"
)
// Mock Service
type Service struct{}
func NewService() *Service {
return &Service{}
}
// === Dig Benchmark ===
func BenchmarkDig(b *testing.B) {
container := dig.New()
_ = container.Provide(NewService) // Provide dependency once
b.ResetTimer()
for i := 0; i < b.N; i++ {
container.Invoke(func(s *Service) {}) // Resolve dependency at runtime
}
}
// === Manual DI Benchmark (Simulating Wire) ===
func BenchmarkManualDI(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = NewService() // Directly instantiate dependency
}
}
// === Wire Injector (Simulated) ===
// Wire generates this function automatically
func InitializeService() *Service {
wire.Build(NewService)
return &Service{}
}
// === Wire Benchmark (Simulated) ===
func BenchmarkWire(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = InitializeService() // Call Wire-generated function
}
}
Run the Benchmark
Run the test using:
go test -bench=.
Expected Results
You'll see output similar to this:
BenchmarkDig-8 50000 32500 ns/op
BenchmarkManualDI-8 1000000 1000 ns/op
BenchmarkWire-8 1000000 950 ns/op
- Wire should be slightly faster than Manual DI.
- Dig should be slower due to runtime reflection overhead.
Summary of Performance Findings
After benchmarking Wire (Compile-Time DI) vs. Dig (Runtime DI), the results show clear trade-offs between performance and flexibility.
Benchmark Results Overview
Approach | Performance | Overhead |
---|---|---|
Manual DI | ✅ Fastest | No extra cost |
Wire (Compile-Time DI) | ✅ Fast | No runtime overhead |
Dig (Runtime DI) | ❌ Slower | Reflection adds overhead |
Key Takeaways
- Wire is faster because it generates Go code at compile time, avoiding any runtime overhead.
- Dig is more flexible but slightly slower due to reflection-based dependency resolution at runtime.
- Manual DI (without any DI framework) remains the fastest but lacks dependency management features.
When to Use Each Approach?
- ✅ Use Wire if performance is a priority and dependencies don’t change often.
- ✅ Use Dig if you need dynamic dependency injection at runtime.
- ✅ Use Manual DI for simple projects where dependency injection is unnecessary.
Would you like a deeper breakdown of the benchmark results or an extended comparison? 🚀
Top comments (0)