Skip to content

Instantly share code, notes, and snippets.

@mjard
Created December 12, 2012 20:30
Show Gist options
  • Select an option

  • Save mjard/4271311 to your computer and use it in GitHub Desktop.

Select an option

Save mjard/4271311 to your computer and use it in GitHub Desktop.

Revisions

  1. mjard created this gist Dec 12, 2012.
    84 changes: 84 additions & 0 deletions bench_interfaces.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,84 @@
    package main

    import (
    "testing"
    )

    func Nop() {
    }

    type Stupid interface {
    Nop()
    }

    type Lame struct {
    }

    func (l Lame) Nop() {
    }

    func BenchmarkNop(b *testing.B) {
    for i := 0; i < b.N; i++ {
    Nop()
    }
    }

    func BenchmarkMemberFunction(b *testing.B) {
    a := Lame{}
    for i := 0; i < b.N; i++ {
    a.Nop()
    }
    }

    func BenchmarkMemberFunctionWithStructPointer(b *testing.B) {
    a := &Lame{}
    for i := 0; i < b.N; i++ {
    a.Nop()
    }
    }

    func AcceptsStupid(s Stupid) {
    s.Nop()
    }

    func BenchmarkInterfaceFunction(b *testing.B) {
    a := Lame{}
    for i := 0; i < b.N; i++ {
    AcceptsStupid(a)
    }
    }

    func BenchmarkInterfaceFunctionWithCast(b *testing.B) {
    a := Lame{}
    for i := 0; i < b.N; i++ {
    AcceptsStupid(Stupid(a))
    }
    }

    func BenchmarkInterfaceFunctionWithCastSaved(b *testing.B) {
    a := Lame{}
    c := Stupid(a)
    for i := 0; i < b.N; i++ {
    AcceptsStupid(c)
    }
    }

    func BenchmarkInterfaceFunctionWithTypeAssert(b *testing.B) {
    a := Lame{}
    c := Stupid(a).(Stupid)
    for i := 0; i < b.N; i++ {
    c.Nop()
    }
    }

    /*
    ---Results---
    BenchmarkNop 2000000000 1.28 ns/op
    BenchmarkMemberFunction 2000000000 1.92 ns/op
    BenchmarkMemberFunctionWithStructPointer 2000000000 1.45 ns/op
    BenchmarkInterfaceFunction 50000000 32.0 ns/op
    BenchmarkInterfaceFunctionWithCast 50000000 32.0 ns/op
    BenchmarkInterfaceFunctionWithCastSaved 100000000 12.7 ns/op
    BenchmarkInterfaceFunctionWithTypeAssert 200000000 8.93 ns/op
    ok local/temp/bench 17.034s
    */