Skip to content

Commit

Permalink
add benchmark samples for go performant tips
Browse files Browse the repository at this point in the history
  • Loading branch information
Bhupesh-V committed Jan 18, 2025
1 parent cb3d5be commit 81afffc
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions go/writing-performant-go-code-megalist.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,28 @@
# Mega List of Tips for Writing Performant Go Code

## Stack vs Heap Allocations

For variable with short lived scope, use non-pointer return value. For variable with long lived scope, use pointer return value. Heap allocation is expensive.

1. For variable with short lived scope, use non-pointer return value. For variable with long lived scope, use pointer return value. Heap allocation is expensive.
2. Use `sync.Pool` for frequently allocated and released objects. Buffer pool is a good example.
3. Use `strings.Builder` in favor of `bytes.Buffer` for string operations.
4. Pre-allcate memory for slices, maps if possible (when using `make()`).
**Benchmark**: https://github.com/Bhupesh-V/pocs/tree/main/go/heap-escape

## Buffer Pools

Use `sync.Pool` for frequently allocated and released objects. Buffer pool is a good example.

**Benchmark**: https://github.com/Bhupesh-V/pocs/tree/main/go/buffer-pool

## Working with strings

Use `strings.Builder` in favor of `bytes.Buffer` for string operations.

## Capping slice length

Pre-allcate memory for slices, maps if possible (when using `make()`).

## Field Alignment in Structs

- https://go.dev/play/p/dNWspo2Dxv
- https://go.dev/play/p/0qsgpuAHHp
- https://itnext.io/structure-size-optimization-in-golang-alignment-padding-more-effective-memory-layout-linters-fffdcba27c61
- https://go101.org/article/memory-layout.html

0 comments on commit 81afffc

Please sign in to comment.