Skip to content

Instantly share code, notes, and snippets.

@ma6174
Created May 11, 2015 15:19
Show Gist options
  • Select an option

  • Save ma6174/982b4ea9f453ce6d7b7f to your computer and use it in GitHub Desktop.

Select an option

Save ma6174/982b4ea9f453ce6d7b7f to your computer and use it in GitHub Desktop.
golang map vs slice sort speed
package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
type S []int
func (s S) Len() int {
return len(s)
}
func (s S) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s S) Less(i, j int) bool {
return s[i] < s[j]
}
type M map[int]int
func (m M) Len() int {
return len(m)
}
func (m M) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}
func (m M) Less(i, j int) bool {
return m[i] < m[j]
}
func main() {
m := M{}
b := []int{}
s := S{}
for i := 0; i < 1000000; i++ {
n := rand.Intn(1000000)
m[i] = n
s = append(s, n)
b = append(b, n)
}
start := time.Now()
sort.Sort(s)
fmt.Println("slice\t", time.Since(start).Seconds())
start = time.Now()
sort.Sort(m)
fmt.Println("map\t", time.Since(start).Seconds())
start = time.Now()
sort.Ints(b)
fmt.Println("int\t", time.Since(start).Seconds())
}
/*
result:
slice 0.29914495900000004
map 3.14801621
int 0.330597454
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment