Skip to content

runtime: append to nil slice slower than make and copy #14718

@nvb

Description

@nvb

Please answer these questions before submitting your issue. Thanks!

  • What version of Go are you using (go version)?
    go version go1.6 darwin/amd64
  • What operating system and processor architecture are you using (go env)?
    GOARCH="amd64" GOOS="darwin"
  • What did you do?
    (Use play.golang.org to provide a runnable example, if possible.)
package main

import (
        "testing"
)

var c =  []byte("1789678900001234567890")

func BenchmarkBBytes(b *testing.B) {
        for i := 0; i < b.N; i++ {
                d := make([]byte, len(c))
                copy(d, c)
        }
}

func BenchmarkBString(b *testing.B) {
        for i := 0; i < b.N; i++ {
                _ = append([]byte(nil), c...)
        }
}
  • What did you expect to see?

The two patterns would produce the same code and have the same performance.

  • What did you see instead?

Instead, the make and copy pattern (BenchmarkBBytes) seems to be faster by about 12 ns, or 16%. See cockroachdb/cockroach#4963.

BenchmarkBBytes-4   20000000            59.6 ns/op        32 B/op          1 allocs/op
BenchmarkBString-4  20000000            71.0 ns/op        32 B/op          1 allocs/op

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions