Created
July 4, 2015 13:31
-
-
Save stanim/7abe87be623c08f2d1a2 to your computer and use it in GitHub Desktop.
Benchmarking ZR
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
$ go test -bench=. | |
testing: warning: no tests to run | |
PASS | |
BenchmarkIntersect1 50000000 29.5 ns/op | |
BenchmarkIntersect2 50000000 35.5 ns/op | |
35.5/29.5 = 1,20 |
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 zr | |
type Point struct { | |
X, Y float64 | |
} | |
type Rectangle struct { | |
Min, Max Point | |
} | |
var ZR Rectangle | |
func (r Rectangle) Intersect1(s Rectangle) Rectangle { | |
if r.Min.X < s.Min.X { | |
r.Min.X = s.Min.X | |
} | |
if r.Min.Y < s.Min.Y { | |
r.Min.Y = s.Min.Y | |
} | |
if r.Max.X > s.Max.X { | |
r.Max.X = s.Max.X | |
} | |
if r.Max.Y > s.Max.Y { | |
r.Max.Y = s.Max.Y | |
} | |
if r.Min.X > r.Max.X || r.Min.Y > r.Max.Y { | |
return ZR | |
} | |
return r | |
} | |
func (r Rectangle) Intersect2(s Rectangle) Rectangle { | |
if r.Min.X < s.Min.X { | |
r.Min.X = s.Min.X | |
} | |
if r.Min.Y < s.Min.Y { | |
r.Min.Y = s.Min.Y | |
} | |
if r.Max.X > s.Max.X { | |
r.Max.X = s.Max.X | |
} | |
if r.Max.Y > s.Max.Y { | |
r.Max.Y = s.Max.Y | |
} | |
if r.Min.X > r.Max.X || r.Min.Y > r.Max.Y { | |
return Rectangle{} | |
} | |
return r | |
} |
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 zr | |
import "testing" | |
var result1, result2 bool | |
func BenchmarkIntersect1(b *testing.B) { | |
r := Rectangle{Point{0, 0}, Point{1, 1}} | |
s := Rectangle{Point{2, 2}, Point{3, 3}} | |
for n := 0; n < b.N; n++ { | |
i := r.Intersect1(s) | |
result1 = i == ZR | |
} | |
} | |
func BenchmarkIntersect2(b *testing.B) { | |
r := Rectangle{Point{0, 0}, Point{1, 1}} | |
s := Rectangle{Point{2, 2}, Point{3, 3}} | |
for n := 0; n < b.N; n++ { | |
i := r.Intersect2(s) | |
result2 = i == Rectangle{} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe they're equivalent w.r.t. performance, see above. So, still curious what was the original reason of introducing ZR & ZP :) As to allocations, I'd expect neither of them is actually GCed, they should both be copied by value (on stack). My suspicion is that the original reason was just to make them easier to write. But I'm still rather surprised they were added.