An intresting behaviour about number of allocations in []byte->string conversions

66 views
Skip to first unread message

T L

unread,
Aug 15, 2020, 12:30:32 AM8/15/20
to golang-nuts

package main

import "fmt"
import "bytes"
import "testing"

const N = 0
var name = bytes.Repeat([]byte{'x'}, N)
var m = make(map[string]string, 10)
var s string

func f
() {
    s
= m[string(name)]
}

func g
() {
    key
:= string(name)
    s
= m[key]
}

func h
() {
    m
[string(name)] = "Golang"
}

func main
() {
    fmt
.Println(testing.AllocsPerRun(1, f)) // 0
    fmt
.Println(testing.AllocsPerRun(1, g)) // 1
    fmt
.Println(testing.AllocsPerRun(1, h)) // 1
}

/* The result:

N          f    g    H
---        ---    ---    ---
>=9        0    1    1
8,4,2,1,0  0    0    0
6,7        0    1    1
3,5        0    1    0
*/


Some inaccuracies in testing.AllocsPerRun?

T L

unread,
Aug 15, 2020, 12:48:45 AM8/15/20
to golang-nuts
Sorry, I temporarily switch to Go 1.3.
The result is constantly 0 0 1 for Go 1.15 when N > 2.
Reply all
Reply to author
Forward
0 new messages