CMap - Concurrent Map for Go
CMap is a high-performance concurrent map implementation for Go, designed to handle concurrent read and write operations efficiently. It uses multiple buckets with individual locks to reduce contention and improve performance in multi-threaded environments.
Features
- High Performance: Optimized for concurrent access with minimal locking.
- Low Contention: Uses multiple buckets to reduce lock contention.
- Scalable: Efficiently handles a large number of entries and concurrent operations.
- Zero Allocations: Minimizes memory allocations during operations.
Installation
To install the cmap package, use go get:
go get github.com/fprotimaru/cmap
Usage
package main
import (
"fmt"
"github.com/fprotimaru/cmap"
)
func main() {
// Create a new CMap with 16 buckets
m := cmap.NewCMap(16)
// Set key-value pairs
m.Set("foo", 42)
m.Set("bar", 100)
// Get values
if value, ok := m.Get("foo"); ok {
fmt.Println("foo:", value)
} else {
fmt.Println("foo not found")
}
if value, ok := m.Get("bar"); ok {
fmt.Println("bar:", value)
} else {
fmt.Println("bar not found")
}
}
Benchmarks
Below are some benchmark results comparing CMap with sync.Map:
BenchmarkSyncMap-8 54,216 18,979 ns/op 5,848 B/op 431 allocs/op
BenchmarkGoCMap-8 102,039 12,055 ns/op 0 B/op 0 allocs/op
BenchmarkSyncMapParallel-8 201,830 5,813 ns/op 5,848 B/op 431 allocs/op
BenchmarkCMapParallel-8 117,099 10,257 ns/op 0 B/op 0 allocs/op
BenchmarkSyncMapWriteMillion-8 2 647,492,396 ns/op 147,442,172 B/op 5,019,931 allocs/op
BenchmarkCMapWriteMillion-8 19 62,507,844 ns/op 11,974,785 B/op 1,001,888 allocs/op