Skip to content

Instantly share code, notes, and snippets.

@freakynit
Created November 28, 2021 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freakynit/69cacf642332aac4ffa207a60b6598a6 to your computer and use it in GitHub Desktop.
Save freakynit/69cacf642332aac4ffa207a60b6598a6 to your computer and use it in GitHub Desktop.
Benchmarking make vs new for slice in golang (https://dev.to/freakynit/using-new-instead-of-make-to-create-slice-17bl)
package main
import (
"fmt"
"time"
)
func testMakeSlice(numIterations int, numRuns int){
a := make([]int32, 0)
for k := 0; k < numRuns; k++ {
for i := 0; i < numIterations; i++ {
a = append(a, 10, 20, 30)
}
}
}
func testNewSlice(numIterations int, numRuns int){
a := new([]int32)
for k := 0; k < numRuns; k++ {
for i := 0; i < numIterations; i++ {
*a = append(*a, 10, 20, 30)
}
}
}
func testNewDereferencedSlice(numIterations int, numRuns int){
a := *new([]int32)
for k := 0; k < numRuns; k++ {
for i := 0; i < numIterations; i++ {
a = append(a, 10, 20, 30)
}
}
}
func benchmark(name string, f func(int, int), numIterations int, numRuns int){
start := time.Now()
f(numIterations, numRuns)
fmt.Println(name, time.Now().Sub(start).Milliseconds()/int64(numRuns), "ms")
}
func warmup(numIterations int, numRuns int){
var s int = 0
for k := 0; k < numRuns; k++ {
for i := 0; i < numIterations; i++ {
s = s + i / 1000
}
}
}
func main() {
var numIterations = 10_000_000
var numRuns = 5
for i := 0; i < 10; i++ {
fmt.Println("===")
benchmark("warmup", warmup, numIterations, numRuns)
benchmark("testMakeSlice", testMakeSlice, numIterations, numRuns)
benchmark("testNewSlice", testNewSlice, numIterations, numRuns)
benchmark("testNewDereferencedSlice", testNewDereferencedSlice, numIterations, numRuns)
}
}
@freakynit
Copy link
Author

Result
===
warmup 5 ms
testMakeSlice 241 ms
testNewSlice 116 ms
testNewDereferencedSlice 55 ms
===
warmup 3 ms
testMakeSlice 50 ms
testNewSlice 55 ms
testNewDereferencedSlice 50 ms
===
warmup 3 ms
testMakeSlice 96 ms
testNewSlice 55 ms
testNewDereferencedSlice 48 ms
===
warmup 3 ms
testMakeSlice 83 ms
testNewSlice 55 ms
testNewDereferencedSlice 48 ms
===
warmup 3 ms
testMakeSlice 49 ms
testNewSlice 55 ms
testNewDereferencedSlice 48 ms
===
warmup 3 ms
testMakeSlice 49 ms
testNewSlice 55 ms
testNewDereferencedSlice 48 ms
===
warmup 3 ms
testMakeSlice 55 ms
testNewSlice 55 ms
testNewDereferencedSlice 48 ms
===
warmup 3 ms
testMakeSlice 49 ms
testNewSlice 54 ms
testNewDereferencedSlice 48 ms
===
warmup 3 ms
testMakeSlice 48 ms
testNewSlice 55 ms
testNewDereferencedSlice 47 ms
===
warmup 3 ms
testMakeSlice 49 ms
testNewSlice 56 ms
testNewDereferencedSlice 48 ms

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