Skip to content

cmd/compile: passing function argument via interface is 16x slower than via typed value #17118

@valyala

Description

@valyala

What version of Go are you using (go version)?

go version devel +67e22a1 Thu Sep 15 17:35:49 2016 +0300 linux/amd64

What operating system and processor architecture are you using (go env)?

GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/aliaksandr/gopath"
GORACE=""
GOROOT="/home/aliaksandr/work/go"
GOTOOLDIR="/home/aliaksandr/work/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build571408045=/tmp/go-build -gno-record-gcc-switches"
CXX="g++"
CGO_ENABLED="1"

What did you do?

I benchmarked the following code:

package main

import "testing"

func BenchmarkEfaceArg(b *testing.B) {
        n := 0
        for i := 0; i < b.N; i++ {
                n += fEface(i)
        }
        if b.N > 0 && n == 0 {
                b.Fatalf("n shouldn't be zero. b.N=%d", b.N)
        }
}

func BenchmarkIntArg(b *testing.B) {
        n := 0
        for i := 0; i < b.N; i++ {
                n += fInt(i)
        }
        if b.N > 0 && n == 0 {
                b.Fatalf("n shouldn't be zero. b.N=%d", b.N)
        }
}

func fEface(v interface{}) int {
        return v.(int)+1
}

func fInt(n int) int {
        return n+1
}

Below are benchmark results:

go test -run=11111 -bench=Arg -benchmem -benchtime=1s
testing: warning: no tests to run
BenchmarkEfaceArg-4     100000000           16.3 ns/op         0 B/op          0 allocs/op
BenchmarkIntArg-4       2000000000           0.98 ns/op        0 B/op          0 allocs/op
PASS

What did you expect to see?

Both benchmarks should run with comparable speed.

What did you see instead?

The benchmark passing the argument via interface to fEface is 16x slower than the benchmark passing the argument to fInt.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions