Xkonti / govec

Go library providing 2D and 3D vector operations
MIT License
6 stars 7 forks source link

Benchmark inlining helper functions #31

Open Xkonti opened 1 year ago

Xkonti commented 1 year ago

Set up benchmarks to compare performance between situations where a small helper function is implemented and where calculations are manually inlined. For example, what is the difference in performance here:

// Helper function 1
func dot(x1 T, y1 T, x2 T, y2 T) T {
    return x1*x2 + y1*y2
}

// Helper function 2
func magnitude(x, y) float64 {
    return math.Sqrt(float64(x*x + y*y))
}

// Using helpers:
func (v V2F[T]) AngleBetweenRad(v2 V2F[T]) float64 {
    dotProduct := dot(v.x, v.y, v2.x, v2.y)
    magnitudeV := magnitude(v.x, v.y)
    magnitudeV2 := magnitude(v2.x, v2.y)
    cosTheta := float64(dotProduct) / (magnitudeV * magnitudeV2)
    return math.Acos(math.Min(math.Max(cosTheta, -1.0), 1.0))
}

// Manually inlined code:
func (v V2F[T]) AngleBetweenRad(v2 V2F[T]) float64 {
    dotProduct := v.X*v2.X + v.Y*v2.Y
    magnitudeV := math.Sqrt(float64(v.X*v.X + v.Y*v.Y))
    magnitudeV2 := math.Sqrt(float64(v2.X*v2.X + v2.Y*v2.Y))
    cosTheta := float64(dotProduct) / (magnitudeV * magnitudeV2)
    return math.Acos(math.Min(math.Max(cosTheta, -1.0), 1.0))
}

This is to decide if the library needs to maintain lots of copy-pasted inlined code or it's safe to extract some of that complexity into reusable functions without reducing performance.