Skip to content

Instantly share code, notes, and snippets.

@func25
Created January 5, 2023 08:37
Show Gist options
  • Save func25/423b8bdf1e3ef8e8984e80aa21491ccd to your computer and use it in GitHub Desktop.
Save func25/423b8bdf1e3ef8e8984e80aa21491ccd to your computer and use it in GitHub Desktop.
Pre-allocating slice, avoid resizing
package main
import (
"fmt"
"time"
)
func main() {
// Allocate a slice with a small capacity
start := time.Now()
s := make([]int, 0, 10)
for i := 0; i < 100000; i++ {
s = append(s, i)
}
elapsed := time.Since(start)
fmt.Printf("Allocating slice with small capacity: %v\n", elapsed) // 1.165208ms
// Allocate a slice with a larger capacity
start = time.Now()
s = make([]int, 0, 100000)
for i := 0; i < 100000; i++ {
s = append(s, i)
}
elapsed = time.Since(start)
fmt.Printf("Allocating slice with larger capacity: %v\n", elapsed) // 361.333µs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment