-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add benchmark samples for go performant tips
- Loading branch information
Showing
1 changed file
with
24 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |