Created
September 6, 2018 21:48
-
-
Save flockonus/70fdb887f00b827b7d686ebe2e381953 to your computer and use it in GitHub Desktop.
Storing MANY structs in memory in Go
This file contains hidden or 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 ( | |
"log" | |
"time" | |
) | |
type Kitty struct { | |
id uint | |
owner string | |
} | |
// how many objects we are creating | |
const limit = 1e6 | |
func main() { | |
kitties := make([]*Kitty, 0, limit) | |
log.Println("oh hi!") | |
t1 := time.Now() | |
for i := 1; i < limit-1; i++ { | |
kitties = append(kitties, &Kitty{uint(i), "kornelius"}) | |
} | |
log.Printf("%s -- done populating -- %d %s", time.Now().Sub(t1), kitties[1e5].id, kitties[1e5].owner) | |
t1 = time.Now() | |
// some dummy calculation over the whole set | |
// avgLen := float64(len(kitties[1e5].owner)) | |
counter := 0 | |
for _, k := range kitties { | |
if k.id > 0 { | |
counter++ | |
} | |
// avgLen = float64(len(k.owner)) / avgLen | |
} | |
// log.Printf("%s -- average kitty name length: %f", time.Now().Sub(t1), avgLen) | |
log.Printf("%s -- kitty brute count: %d", time.Now().Sub(t1), counter) | |
t1 = time.Now() | |
time.Sleep(time.Second * 12) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ go run main.go
2018/09/06 14:46:26 oh hi!
2018/09/06 14:46:26 127.415211ms -- done populating -- 100001 kornelius
2018/09/06 14:46:26 2.757098ms -- kitty brute count: 999998