Created
February 13, 2014 03:27
-
-
Save collinvandyck/8969241 to your computer and use it in GitHub Desktop.
pass by value vs pass by reference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) { | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
BenchmarkPassByValue 500000000 7.87 ns/op | |
BenchmarkPassByPointer 2000000000 0.30 ns/op |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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