FAQ
I'm not sure, but is this intended behavior? In the following code, calling
foo on bar causes an allocation, while calling foo on baz does not. I
assume this is because bar is not an interface value, and thus, the runtime
needs to allocate a GoInterface struct for bar. Is there a reason that this
is not allocated on the stack?

var bar string = "hello"
var baz interface{} = "hello"

func foo(val interface{}) {}

func main() {
ms1, ms2 := new(runtime.MemStats), new(runtime.MemStats)

runtime.GC()
runtime.ReadMemStats(ms1)
for i := 0; i < 1000; i++ {
foo(bar)
}
runtime.ReadMemStats(ms2)
fmt.Println("NumMallocs:", ms2.Mallocs-ms1.Mallocs) // 1000 mallocs
fmt.Println("TotalAlloc:", ms2.TotalAlloc-ms1.TotalAlloc)

runtime.GC()
runtime.ReadMemStats(ms1)
for i := 0; i < 1000; i++ {
foo(baz)
}
runtime.ReadMemStats(ms2)
fmt.Println("NumMallocs:", ms2.Mallocs-ms1.Mallocs) // 0 mallocs
fmt.Println("TotalAlloc:", ms2.TotalAlloc-ms1.TotalAlloc)
}

Playground <https://play.golang.org/p/0DI_hVrebj>

--
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 8 | next ›
Discussion Overview
groupgolang-nuts @
categoriesgo
postedJul 10, '15 at 12:53a
activeJul 10, '15 at 4:36a
posts8
users4
websitegolang.org

People

Translate

site design / logo © 2021 Grokbase