Created
October 13, 2021 09:24
-
-
Save scrouthtv/73f1bc9494d37593e91f148b2a207191 to your computer and use it in GitHub Desktop.
Go append vs prepend
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 app | |
import "testing" | |
import "math/rand" | |
func BenchmarkAppend(b *testing.B) { | |
arr := make([]int, 5) | |
for i, _ := range arr { | |
arr[i] = rand.Int() | |
} | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
_ = append(arr, 5) | |
} | |
} | |
func BenchmarkPrepend(b *testing.B) { | |
arr := make([]int, 5) | |
for i, _ := range arr { | |
arr[i] = rand.Int() | |
} | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
_ = append([]int{5}, arr...) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I used this to compare the performance of adding a single item
Output on my machine:
Surprisingly, prepending is faster than appending.