Skip to content

Instantly share code, notes, and snippets.

@sunjayaali
Created July 7, 2021 08:27
Show Gist options
  • Save sunjayaali/cf6e5b205d75286a839cf5e31e238171 to your computer and use it in GitHub Desktop.
Save sunjayaali/cf6e5b205d75286a839cf5e31e238171 to your computer and use it in GitHub Desktop.
Go append slice speed comparison
package main
import (
"fmt"
"strconv"
"sync"
"time"
)
func method(f func()) func() {
return func() {
defer func(begin time.Time) {
fmt.Println(time.Since(begin))
}(time.Now())
f()
}
}
func routine(n int, f func()) func() {
return func() {
wg := &sync.WaitGroup{}
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
defer wg.Done()
f()
}()
}
wg.Wait()
}
}
func main() {
n := 1000000
numRoutine := 100
method1 := func() {
nums := []string{}
for i := 0; i < n; i++ {
nums = append(nums, strconv.Itoa(i))
}
}
method2 := func() {
nums := make([]string, n)
for i := 0; i < n; i++ {
nums[i] = strconv.Itoa(i)
}
}
method3 := func() {
nums := make([]string, 0, n)
for i := 0; i < n; i++ {
nums = append(nums, strconv.Itoa(i))
}
}
method(routine(numRoutine, method1))()
method(routine(numRoutine, method2))()
method(routine(numRoutine, method3))()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment