Created
November 28, 2021 08:36
-
-
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)
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 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result