FAQ
Hi,

I stumbled upon an extra allocation in a benchmark using dynamic
dispatch and I can't really figure out when it occurs and how to avoid it.
At first glance it seems it's when you do dynamic dispatch of a function
taking an interface{} as argument.
But that doesn't seem to be the whole truth.

Here's an example of the allocation I'm taking about:
========================================================

type K interface {
  s(*thing, int)
  d(*thing, interface{})
}

type thing struct {}

func (t *thing) d(val interface{}) {
}

func (t *thing) s(val int) {
}

type thinger struct {}

func (g *thinger) d(t *thing, val interface{}) {
  t.d(val)
}
func (g *thinger) s(t *thing, val int) {
  t.s(val)
}

func BenchmarkIfaceSD(b *testing.B) {
  var k *thinger
  t := &thing{}
  k = &thinger{}

  for i := 0; i < b.N; i++ {
   k.d(t,42)
  }
}

func BenchmarkIfaceDS(b *testing.B) {
  var k K
  t := &thing{}
  k = &thinger{}

  for i := 0; i < b.N; i++ {
   k.s(t,42)
  }
}

func BenchmarkIfaceSS(b *testing.B) {
  var k *thinger
  t := &thing{}
  k = &thinger{}

  for i := 0; i < b.N; i++ {
   k.s(t,42)
  }
}

func BenchmarkIfaceDD(b *testing.B) {
  var k K
  t := &thing{}
  k = &thinger{}

  for i := 0; i < b.N; i++ {
   k.d(t,42)
  }
}
========================================

go test -bench Iface -benchmem

BenchmarkIfaceSD-4 100000000 10.9 ns/op 0 B/op 0
allocs/op
BenchmarkIfaceDS-4 1000000000 2.01 ns/op 0 B/op 0
allocs/op
BenchmarkIfaceSS-4 2000000000 0.33 ns/op 0 B/op 0
allocs/op
BenchmarkIfaceDD-4 50000000 29.6 ns/op 8 B/op 1
allocs/op


What's the rules for avoiding that allocation in the last test?

/Peter

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Discussion Posts

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 1 of 7 | next ›
Discussion Overview
groupgolang-nuts @
categoriesgo
postedMay 26, '16 at 1:06p
activeMay 27, '16 at 6:52a
posts7
users3
websitegolang.org

People

Translate

site design / logo © 2021 Grokbase