savi-lang / savi

A fast language for programmers who are passionate about their craft.
BSD 3-Clause "New" or "Revised" License
156 stars 12 forks source link

Optimize boxing for numerics in type unions #134

Open jemc opened 3 years ago

jemc commented 3 years ago

Currently when we need to put a numeric value into a type union we will heap-allocate a wrapper object that contains the numeric value, so that it can fit in the same size as other pointers and have a type descriptor for runtime type matching. This is the same as what Pony does.

However, there are more efficient ways to wrap some numerics.

Floating-point numerics and integer numerics whose size is small enough to fit inside 52 bits can use "NaN boxing", encoded as an F64 NaN value with the 52 mantissa bits that are not used by the NaN encoding being used to encode the actual value, with the first few of those 52 bits being used to discriminate which numeric type is being used. A 64-bit pointer type whose value can (usually?) be counted on to have no more than 52 significant bits can also be encoded as a NaN, using the sign bit of the F64 encoding as a flag to indicate whether the 52 mantissa bits refer to a numeric type or a pointer.

In this way, we could make certain type unions much more efficient, avoiding a heap allocation for the wrapping of them while still keeping them in a consistent and comprehensible representation.

jemc commented 2 years ago

Note that this ticket has some overlap with #96.