I have two examples of the similar program written on Go. Main aim of that code is sort map of structs using value in the struct.
Example with pointers
package main
import (
"fmt"
"sort"
)
type payload struct {
data string
value float64
}
type container struct {
counter int
storage map[int]*payload
}
type payloadSlice []*payload
// Len is part of sort.Interface.
func (p payloadSlice) Len() int {
return len(p)
}
// Swap is part of sort.Interface.
func (p payloadSlice) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
// Less is part of sort.Interface. We use count as the value to sort by
func (p payloadSlice) Less(i, j int) bool {
return p[i].value < p[j].value
}
func main() {
name := "special_unique_name"
var m = map[string]container{
name: {counter: 10, storage: map[int]*payload{
5: {data: "epsilon", value: 55},8: {data: "theta", value: 85},4: {data: "delta", value: 48},1: {data: "alpha", value: 14},10: {data: "kappa", value: 101},
3: {data: "gamma", value: 31},6: {data: "zeta", value: 63},2: {data: "beta", value: 26},9: {data: "iota", value: 92},7: {data: "eta", value: 79},
}},
}
s := make(payloadSlice, 0, len(m[name].storage))
for _, v := range m[name].storage {
s = append(s, v)
}
sort.Sort(s)
for _, v := range s {
fmt.Println(name, v)
}
}
Examples with values
package main
import (
"fmt"
"sort"
)
type payload struct {
data string
value float64
}
type container struct {
counter int
storage map[int]payload
}
type payloadSlice []payload
// Len is part of sort.Interface.
func (p payloadSlice) Len() int {
return len(p)
}
// Swap is part of sort.Interface.
func (p payloadSlice) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
// Less is part of sort.Interface. We use count as the value to sort by
func (p payloadSlice) Less(i, j int) bool {
return p[i].value < p[j].value
}
func main() {
name := "special_unique_name"
var m = map[string]container{
name: {counter: 10, storage: map[int]payload{
5: {data: "epsilon", value: 55},8: {data: "theta", value: 85},4: {data: "delta", value: 48},1: {data: "alpha", value: 14},10: {data: "kappa", value: 101},
3: {data: "gamma", value: 31},6: {data: "zeta", value: 63},2: {data: "beta", value: 26},9: {data: "iota", value: 92},7: {data: "eta", value: 79},
}},
}
s := make(payloadSlice, 0, len(m[name].storage))
for _, v := range m[name].storage {
s = append(s, v)
}
sort.Sort(s)
for _, v := range s {
fmt.Println(name, v)
}
}
I'd like to know 2 moments:
Which example will be memory-efficient? (I guess it's a pointer way)
How to measure performance of these examples, using test data with with different number of structs inside the map? Can you help me with creating Benchmark?
I suppose the size of each struct in the map will vary from 1-2kB in average.