For some of the builtin math functions, there exists a function in std.math
with the same name that is basically a wrapper around the builtin. Some examples are @sin
and std.math.sin
, @cos
and std.math.cos
, and @round
and std.math.round
. In these cases, is it best practice to use the builtin function or the standard library function? It is two ways to do the same thing, so I’m not sure which is more idiomatic.
One thing I noticed is that you can’t assign builtin functions to named constants. For example, the following gives a compile error:
const sin = @sin;
Of course, this works:
const sin = std.math.sin;
If both std.math.foo
and @foo
exist, it usually means that the math function is a leftover from before the builtin was implemented. If the math function wraps the builtin, there’s probably no observable difference between the two and they will likely generate identical code under optimized release modes, but you should probably still prefer the builtin because the math function might be removed in the future.
Math functions might be promoted to builtins is if doing so enables special optimizations and/or mapping the operation to hardware instructions. For example, x87 has dedicated instructions for sin/cos, so the compiler may or may not choose to map @sin
/@cos
to those instructions instead of computing the result in software depending on performance and accuracy characteristics. If you’re curious about which math builtins might get added in the future, there is an accepted proposal to add builtins for all relevant LLVM intrinsics.
4 Likes