Created
March 8, 2025 15:10
-
-
Save fabianoflorentino/4fd57180af9cbe5a715dd1be380b4440 to your computer and use it in GitHub Desktop.
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() { | |
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)) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment