FAQ
It's interesting. According to blog
<http://blog.golang.org/laws-of-reflection> posts
<http://research.swtch.com/interfaces>, an interface is represented as a
pair (pointer to concrete value, type descriptor) and should be allocated
"on the stack". The interface should contain a pointer to bar, but the
interface itself should not be boxed on the heap. I'm wondering what's
happening here. I'm pretty sure I'm missing something, as it always turns
out :)
On Friday, July 10, 2015 at 2:53:29 AM UTC+2, thebroke...@gmail.com wrote:

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

Previous

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 2 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