Skip to content

Instantly share code, notes, and snippets.

@scorredoira
Last active October 10, 2021 23:30
Show Gist options
  • Save scorredoira/36f20afc6ac5accd2a28 to your computer and use it in GitHub Desktop.
Save scorredoira/36f20afc6ac5accd2a28 to your computer and use it in GitHub Desktop.
package test
import (
"math/rand"
"testing"
"time"
)
type Customer struct {
Id int
Inv Invoice
}
type Invoice struct {
IdCustomer int
}
var count = 60
var customers []Customer
var invoices []Invoice
func init() {
customers = make([]Customer, count)
invoices = make([]Invoice, count)
rand.Seed(time.Now().UnixNano())
for i := 0; i < count; i++ {
r := rand.Intn(count)
customers[i] = Customer{Id: r}
invoices[i] = Invoice{r}
}
}
func BenchmarkMap(b *testing.B) {
for n := 0; n < b.N; n++ {
// Initialize a map
m := make(map[int]Invoice, len(invoices))
for _, i := range invoices {
m[i.IdCustomer] = i
}
// this will find the element almost instantly but we had to
// initialize the map first.
for _, c := range customers {
c.Inv = m[c.Id]
}
}
}
func BenchmarkSlice(b *testing.B) {
for n := 0; n < b.N; n++ {
// search by iterating until we find it
for _, i := range invoices {
for _, c := range customers {
if i.IdCustomer == c.Id {
c.Inv = i
break
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment