0 day streak
Code library

Code worth reading.

Hand-picked snippets across TypeScript, Python, Rust, Go, and more — each one comes with a line-by-line breakdown so you can read it like the people who wrote it.

3495 snippets · 10 languages
▶ Start learning
Go · ExpertSnippet

Optimizing Struct Memory Alignment

Go aligns struct fields based on their size. Large fields should come first to minimize padding bytes added by the compiler to ensure memory address alignment.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
type Optimized struct {
A int64 // 8 bytes
B int32 // 4 bytes
C bool // 1 byte
} // Total: 16 bytes (3 bytes padding)
type Unoptimized struct {
C bool // 1 byte
A int64 // 8 bytes (7 bytes padding!)
B int32 // 4 bytes
} // Total: 24 bytes
Data TypesPerformance
Go · ExpertSnippet

Reducing GC Pressure with sync.Pool

sync.Pool allows for object reuse, significantly reducing the frequency of garbage collection cycles in high-throughput applications by recycling allocated memory.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
var bufferPool = sync.Pool{
New: func() any { return new(bytes.Buffer) },
}
func Process(data []byte) {
buf := bufferPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
bufferPool.Put(buf)
}()
buf.Write(data)
}
PerformanceDesign PatternsAsync & Concurrency
Go · ExpertSnippet

Zero-Allocation String to Byte Slice Conversion

Standard conversions copy memory. Using the unsafe package allows reinterpreting the underlying memory header to avoid allocations, though it requires careful management of string immutability.

snippet.go
go
1
2
3
4
5
6
7
func StringToBytes(s string) []byte {
return unsafe.Slice(unsafe.StringData(s), len(s))
}
func BytesToString(b []byte) string {
return unsafe.String(unsafe.SliceData(b), len(b))
}
PerformanceBest PracticesData Types
Go · ExpertSnippet

Generic Type Set Constraints

Type sets in interfaces allow generics to restrict types to a specific union. The tilde (~) operator includes types that share the same underlying primitive type.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
type Number interface {
~int | ~int64 | ~float64
}
func Sum[T Number](vals []T) T {
var total T
for _, v := range vals {
total += v
}
return total
}
SyntaxData TypesFunctions
Go · ExpertSnippet

Request Collapsing with singleflight

The singleflight package provides a duplicate function call suppression mechanism. It ensures that for a given key, only one execution of a function is in flight at a time. If multiple goroutines call Do with the same key simultaneously, the first one triggers the function execution, and the others wait to receive the exact same result once it's ready, effectively preventing 'thundering herd' problems on downstream services.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
var g singleflight.Group
func fetchData(key string) (interface{}, error) {
v, err, shared := g.Do(key, func() (interface{}, error) {
return callExpensiveAPI(key)
})
if shared {
log.Printf("Result for %s was shared", key)
}
return v, err
}
PerformanceDesign Patterns
Go · ExpertSnippet

High-Concurrency Map with Lock Striping

Lock striping is a pattern to reduce contention on a shared resource by splitting it into multiple independent 'shards', each with its own lock. In a highly concurrent environment, a single global mutex on a map becomes a bottleneck. By hashing the key to select a shard, multiple goroutines can read and write to different parts of the map simultaneously.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
type Shard struct {
sync.RWMutex
m map[string]string
}
type ShardedMap []*Shard
func (s ShardedMap) getShard(key string) *Shard {
return s[uint32(crc32.ChecksumIEEE([]byte(key)))%uint32(len(s))]
}
func (s ShardedMap) Get(key string) string {
shard := s.getShard(key)
shard.RLock()
defer shard.RUnlock()
return shard.m[key]
}
PerformanceDesign Patterns
Go · ExpertSnippet

Profiling Specific Logic with pprof Labels

Standard CPU profiling in Go shows where time is spent across functions, but often doesn't distinguish between different contexts (e.g., which specific user or task caused the load). pprof.Do allows you to attach key-value labels to a goroutine's context. When a CPU profile is taken, these labels are recorded, allowing you to filter the resulting profile by specific categories.

snippet.go
go
1
2
3
4
5
6
func processUserRequest(ctx context.Context, userID string) {
labels := pprof.Labels("worker", "image-processor", "user_id", userID)
pprof.Do(ctx, labels, func(ctx context.Context) {
expensiveTransformation(ctx)
})
}
PerformanceTesting
Go · ExpertSnippet

Resource Throttling with Weighted Semaphores

Weighted semaphores allow you to control access to a shared resource pool where different tasks may consume different amounts of that resource. Unlike a simple channel-based semaphore which only counts units, the weighted semaphore can grant access based on a variable 'cost' per operation, making it ideal for managing memory-intensive or CPU-bound tasks with varying weights.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
var sem = semaphore.NewWeighted(100)
func handleRequest(ctx context.Context, cost int64) error {
if err := sem.Acquire(ctx, cost); err != nil {
return err
}
defer sem.Release(cost)
doHeavyWork()
return nil
}
Async & ConcurrencyDesign Patterns