Skip to content

Instantly share code, notes, and snippets.

@stanim
Created July 4, 2015 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stanim/7abe87be623c08f2d1a2 to your computer and use it in GitHub Desktop.
Save stanim/7abe87be623c08f2d1a2 to your computer and use it in GitHub Desktop.
Benchmarking ZR
$ 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
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
}
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{}
}
}
@akavel
Copy link

akavel commented Jul 5, 2015

C:\prog\tmp\test-go-ZR>%goroot%\bin\go test -bench=. -cpu=1
testing: warning: no tests to run
PASS
BenchmarkIntersect1     100000000               25.2 ns/op
BenchmarkIntersect2     50000000                28.1 ns/op
ok      _/C_/prog/tmp/test-go-ZR        4.211s

C:\prog\tmp\test-go-ZR>%goroot%\bin\go test -bench=. -cpu=1
testing: warning: no tests to run
PASS
BenchmarkIntersect1     100000000               28.4 ns/op
BenchmarkIntersect2     50000000                25.6 ns/op
ok      _/C_/prog/tmp/test-go-ZR        4.407s

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.

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