Created
January 5, 2023 08:37
-
-
Save func25/423b8bdf1e3ef8e8984e80aa21491ccd to your computer and use it in GitHub Desktop.
Pre-allocating slice, avoid resizing
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
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