FAQ
Because it makes a copy of the data and it puts a pointer to the data copy
in the interface. If you are instead calling foo(&bar) you will see 0
mallocs.

Now why it does it for the string, I'm not sure, strings are immutable so
you would think it could be optimized to just have a pointer to an interned
string. Perhaps it's just not yet optimized or I'm missing something else
as I'm very new to Go.

On Thursday, July 9, 2015 at 7:20:35 PM UTC-7, Roberto Zanotto wrote:

Playing a bit on the playground helped me figure out something. If you
change the type of bar (here with [32]byte
<https://play.golang.org/p/_QJWcAiz26>) it's allocating exactly the
amount of memory needed to store 1000 of those variables. So it looks like
it's not storing the interfaces on the heap, but it's re-allocating bar
when assigning it to interface{}. Still trying to understand why...
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 | 4 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