Skip to content

Instantly share code, notes, and snippets.

@collinvandyck
Created February 13, 2014 03:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save collinvandyck/8969241 to your computer and use it in GitHub Desktop.
Save collinvandyck/8969241 to your computer and use it in GitHub Desktop.
pass by value vs pass by reference
package main
import "testing"
type Stuff struct {
Hello string
Goodbye string
Slice []string
}
func NewStuff() Stuff {
return Stuff{
Hello: "hello!",
Goodbye: "goodbye!",
Slice: []string{"dogs", "are", "pretty", "cool"},
}
}
func BenchmarkPassByValue(b *testing.B) {
stuff := NewStuff()
for i := 0; i < b.N; i++ {
byValue(stuff)
}
}
func BenchmarkPassByPointer(b *testing.B) {
stuff := NewStuff()
for i := 0; i < b.N; i++ {
byPointer(&stuff)
}
}
func byPointer(stuff *Stuff) {
}
func byValue(stuff Stuff) {
}
BenchmarkPassByValue 500000000 7.87 ns/op
BenchmarkPassByPointer 2000000000 0.30 ns/op
@rogpeppe
Copy link

A fairer comparison in many circumstances would be:

func BenchmarkPassByValue(b *testing.B) {
for i := 0; i < b.N; i++ {
stuff := NewStuff()
byValue(stuff)
}
}

func BenchmarkPassByPointer(b *testing.B) {
for i := 0; i < b.N; i++ {
stuff := NewStuff()
byPointer(&stuff)
}
}

because passing by pointer often implies you must create
a pointer to pass. The difference then is considerably
smaller (i see 42.7ns vs 34.2).

And if the pointer escapes (as is not uncommon) then the
by-value option is considerably better (50ns vs 109ns)

I used this code:
http://play.golang.org/p/B17c5pBWH6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment