Skip to content

Cache trig and combine deg2rad in heading()#16

Merged
gistrec merged 1 commit into
masterfrom
optimize-spherical-heading
May 9, 2026
Merged

Cache trig and combine deg2rad in heading()#16
gistrec merged 1 commit into
masterfrom
optimize-spherical-heading

Conversation

@gistrec
Copy link
Copy Markdown
Owner

@gistrec gistrec commented May 9, 2026

Optimize heading() hot-path

Two micro-optimizations in geo::heading() — it's called in every bearing calculation, so each saved instruction adds up.

Combine two deg2rad calls into one
Instead of converting from.lng and to.lng separately and subtracting, compute deg2rad(to.lng - from.lng). Algebraically identical (a*k - b*k == (a - b)*k), one fewer multiplication, and the from-side longitude is no longer needed in radians at all.

Cache sin / cos of latitudes
cos(to_lat), sin(to_lat), cos(from_lat), sin(from_lat) each appeared twice in the atan2 arguments. Without -ffast-math, the compiler is not allowed to CSE calls to std::sin / std::cos because they may touch the floating-point environment (errno, FE flags). Storing them in locals forces a single libm call per value — cuts trig calls in this function from 8 to 4.

Behavior is unchanged — codegen only

@gistrec gistrec requested a review from MrHerrn May 9, 2026 13:16
@gistrec gistrec self-assigned this May 9, 2026
@gistrec gistrec merged commit 7b9a7f1 into master May 9, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants