Skip to content

Instantly share code, notes, and snippets.

@fabianoflorentino
Created March 8, 2025 15:10
Show Gist options
  • Save fabianoflorentino/4fd57180af9cbe5a715dd1be380b4440 to your computer and use it in GitHub Desktop.
Save fabianoflorentino/4fd57180af9cbe5a715dd1be380b4440 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
)
func main() {
const (
numElements = 10_000_000_0
)
start := time.Now()
var dynamicSlice []int
for idx := range numElements {
dynamicSlice = append(dynamicSlice, idx)
}
fmt.Println("Time to create dynamic slice: ", time.Since(start))
fmt.Println("Length: ", len(dynamicSlice))
fmt.Println("Capacity: ", cap(dynamicSlice))
start = time.Now()
preAllocatedSlice := make([]int, 0, numElements)
for idx := range numElements {
preAllocatedSlice = append(preAllocatedSlice, idx)
}
fmt.Println("Time to create pre-allocated slice: ", time.Since(start))
fmt.Println("Length: ", len(preAllocatedSlice))
fmt.Println("Capacity: ", cap(preAllocatedSlice))
}
@fabianoflorentino
Copy link
Author

image

@fabianoflorentino
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment