binary performance

Contract

Performance thresholds, limb layout, NTT primes, scratch storage, and fallback selection are implementation details. Public results, flags, and interchange bits must be identical across algorithms and targets.

Representation

Non-JS targets use inline 64/128-bit coefficients and little-endian 64-bit limbs above 128 bits; JavaScript uses a hidden host bigint adapter. The public BinCoeff type keeps that backend choice unobservable. The move from 32-bit to 64-bit limbs (issue #19) is staged: addition, subtraction, comparison, shifts, the schoolbook multiplication and squaring, and the Karatsuba and Toom-3 steps work on 64-bit limbs; division, the square-root kernels and the NTT still read a 32-bit view of the same storage until their stages. A 64-bit limb product needs the high half of a 64 by 64 bit multiplication, which MoonBit has no instruction for, so it is computed from four 32 by 32 bit products on every target; the schoolbook kernel is still 2.7 to 3.7 times faster on Native and 1.7 to 1.9 times on Wasm-GC because it runs a quarter of the limb steps. Paired Native runs of the whole stage: 2,048 to 8,192-bit multiplication 2.2 times faster, 8,192-bit addition 2.3 times, exp and ln at 2,048 bits 2.0 times. On Wasm and Wasm-GC multiplication below about 6,000 bits is 1.3 to 1.7 times faster; above about 9,000 bits the Karatsuba step, which allocates a coefficient for every intermediate value, is up to 1.8 times slower until the next stage moves it to limb arrays.

Fixed-point exponential

The certified exp enclosure bounds the Taylor series of the reduced argument (at most 1/8) in fixed point with 16 fractional bits beyond the working precision when the argument is exact at the working precision, instead of with one rounded floating-point operation per term. Each computed term rounds down, so their sum is a lower bound; each carries an error below 3 units of the last place, which gives an upper bound with a rigorous tail. The enclosure is about as wide as the floating-point one, the 12-attempt refinement loop and its working precisions are unchanged, and arguments that are not exact at the working precision still use the previous series. White-box tests check that the enclosure contains a much tighter one and that the final correctly rounded results and flags equal those of the previous series. Paired runs: exp is 9 to 10 times faster on Native at 53 to 2,048 bits, 7 to 11 times on Wasm and Wasm-GC, and decimal exp 1.7 to 2.2 times.

Multiplication

Balanced multiplication uses schoolbook below 32 64-bit limbs (2,048 bits on Native, LLVM, Wasm and Wasm-GC), then Karatsuba on limb arrays (a few small temporaries per step, no intermediate BinCoeff), Toom-3, and a two-prime Montgomery NTT with CRT when transform bounds fit. Unbalanced inputs use block multiplication or overlap-add. Native and LLVM select Toom-3 and NTT multiplication at 4,096 64-bit limbs and NTT square at 3,584; Wasm and Wasm-GC at 2,048 and 1,536 (the values of the version before the 64-bit limbs, 4,096 and 3,072 in 32-bit limbs, halved; not measured again on those targets). A 64-bit limb product costs four i64.mul on Wasm, so from 160 limbs (10,240 bits) Wasm and Wasm-GC split the operands into 32-bit limbs, multiply there with the same Karatsuba and pack the result back (the conversions are linear); squaring uses the 32-bit half-product schoolbook from 80 limbs. Native square dispatch switches from specialized schoolbook to recursive multiplication at 512 limbs; other targets retain the previous 768-limb boundary. Cutoffs measured per target with paired runs of coefficient multiplication at 1,024 to 65,536 bits. Paired runs against the 32-bit implementation: coefficient multiplication is 2 to 3 times faster on Native from 1,024 to 32,768 bits, 1.1 to 2.2 times on Wasm-GC and 1.1 to 2.1 times on Wasm; Binary mul 1.6, 2.5 and 2.9 times faster at 512, 2,048 and 8,192 bits on Native, add 1.9 and 2.4 times at 2,048 and 8,192 bits, sqrt 1.5 and 2.0 times at 2,048 and 8,192 bits.

Single-word fast paths

Binary::add, mul, div and sqrt on operands whose coefficients fit one machine word (up to 64 bits) and whose precision is at most 62 bits (60 for div and sqrt) skip the general path, which builds several coefficient values, a context, a flags record and a result tuple for each operation. The fast path computes on UInt64 pairs (128-bit sums and products, a 128 by 64 bit division, a double-precision estimate refined by a Newton step and settled by exact comparisons for the square root), rounds to nearest even with the round and sticky bits, and allocates only the result. It declines a NaN, an infinity, a zero, an exact zero sum, wider coefficients or precision, operands whose exponents are far apart or near the implementation limits, and JavaScript, where the general path answers; the results are the same values with the same precision and exponent. White-box tests compare 40,000 random operand pairs per operation, ties, carries, cancellation and perfect squares with the general path. Paired native runs at 53 bits: add 2.9 times faster, mul 3.0, div 4.9, sqrt 2.8; on Wasm 3.1 to 5.1 times and on Wasm-GC 3.9 to 7.6 times. Operands of 128 bits and more are unchanged.

Two-word and coefficient fast paths

Above the single-word range, Binary::add and mul on coefficients of up to 128 bits at a precision of at most 128 bits run on UInt64 words as well: a 192-bit aligned sum or difference and a 256-bit product (four word products, the high halves by 32-bit pieces), rounded to nearest even from the words with the round and sticky bits, and only the result is allocated. Wider operands, and div and sqrt at any size, go through coefficient-level paths that do the same exact integer arithmetic as the general path but skip its context, flags record, result tuple and repeated rounding decisions: the sum is built in one array (up to 24 words, then whole-coefficient shifts and one addition), the product is the existing BinCoeff product, the quotient carries at least two bits more than the precision plus a sticky bit from the remainder, the square root rounds from the integer root and its remainder (remainder > root decides, there are no ties), and the kept bits are copied once into the array that becomes the coefficient. Each path declines a NaN, an infinity, a zero, an exact zero sum, coefficients or precisions above 2^20 bits, operands whose exponents are far apart or near the implementation limits, and JavaScript, where the general path answers; the results are the same values with the same precision and exponent. White-box tests compare tens of thousands of random, all-ones, sparse, tie, exact-quotient, perfect-square and cancelling operand sets per operation with the general path on Native, Wasm and Wasm-GC (JavaScript keeps the general path). Paired runs against the previous build: add 3.3 times and mul 3.5 times faster at 128 bits on Native (2.5 and 3.7 on Wasm-GC, 3.5 and 3.0 on Wasm), 1.9 to 2.2 times at 256 bits, 1.5 to 1.9 times at 512 bits and 1.2 times at 1,024 bits; sqrt 1.4 times at 128 bits (1.9 on Wasm-GC) and 1.1 at 512 and 2,048 bits; div 1.1 to 1.2 times at 128 to 512 bits, where the Knuth division dominates.

Fixed-point sine and cosine

The Taylor series of sin and cos on the reduced argument (at most 1 in magnitude) is summed in fixed point when the argument is exact at the working precision, with 20 guard bits and, for the sine, the leading zero bits of the argument, so a small argument keeps precision + 20 significant bits. Each computed term rounds down and is short by at most 4 units, the series alternates with decreasing terms, and so signed sum +- (4n + 28) encloses the value, with the sign flipped for a negative sine argument. Arguments that are not exact, or so small that the guard bits would exceed four times the working precision, use the previous floating-point series; the refinement loop and its working precisions are unchanged. White-box tests check containment of a much tighter enclosure, a bound on the width, and the sine and cosine identities. Paired runs on top of the memoized constants (without them the pi recomputation hides the series): sin is 4.3 to 5.7 times faster on Native at 53 to 2,048 bits and 4.6 times on Wasm-GC; on its own the change gives 1.3 to 1.4 times, because the series is about nine tenths of the time only once pi is cached.

Division, square root and GCD

Division uses a one-limb path, Knuth’s algorithm D on 64-bit digits (a 128 by 64 bit quotient estimate and a 128-bit correction test) below the Burnikel–Ziegler cutoff (also as the leaf of its recursion, up to 64 limbs of 64 bits), and Burnikel–Ziegler from 96 limbs of 64 bits (192 of 32 bits) on Wasm, Wasm-GC and LLVM and from 208, 352 or 752 limbs of 64 bits on Native, with the portable, C or assembly rows. Newton reciprocal division is no longer selected: once multiplication was 2 to 3 times faster it was 3 to 12 times slower than Burnikel–Ziegler from 32,768 bits (4.4 ms against 0.37 ms at 32,768 bits), so the dispatch never reaches it; the routine stays, covered by tests, and the threshold constant is per target. Paired runs against the previous kernels: div is 1.5, 2.3 and 2.9 times faster on Native at 512, 2,048 and 8,192 bits, 1.9 and 3.3 times on Wasm-GC and 1.3 and 3.3 times on Wasm at 2,048 and 8,192 bits, and the sqrt of 8,192 bits 1.5 to 1.8 times faster on all three; native multiplication switched to the NTT at 8,192 limbs of 32 bits (4,096 limbs of 64 bits, see Multiplication) instead of 2,048 limbs of 32 bits now that the Karatsuba is faster. Square root uses fixed-width kernels through 256 bits (the word kernels on Native, LLVM and Wasm-GC, the restoring loops on linear Wasm) and Zimmermann’s SqrtRem on word arrays above that on every target except JavaScript; the recursion stops at the same fixed-width kernels once a block is at most 256 bits (a restoring loop on heap integers at 128 bits before), which makes a 1,024-bit radicand (a 512-bit sqrt) about 3.4 times faster on Native and 3.1 to 3.3 times on Wasm in paired runs. The cutoff is per-target policy measured with paired runs; the LLVM value is not measured because that backend is not available in the toolchain used. Large GCD uses Lehmer batching on a common 63-bit window of both operands and takes a single division step when the shorter operand has no bits in that window, so operands of very different lengths are reduced at once.

The integer square root of a value of up to 256 bits (a 128-bit root, the base case of the divide-and-conquer root and the whole root at precisions up to 128 bits) no longer runs a bit-by-bit loop on Native, LLVM and Wasm-GC: up to 128 bits it is a double-precision estimate refined by one Newton step on 128-bit arithmetic and settled by exact comparisons, and up to 256 bits Zimmermann’s word-level Karatsuba square root (the root of the upper two words, one 128 by 64 bit division for the low half, an exact settle on the 256-bit square) on a value normalized by an even shift. Values of 257 to 512 bits on Native and LLVM go through the divide-and-conquer root with that base case instead of the 512-bit loop. Linear Wasm keeps the loops (its 64-bit multiplication makes the word kernels no faster there), and the Wasm targets keep the 512-bit base case. Paired runs against the previous kernels (with the coefficient-level paths above): sqrt at 100 and 128 bits 2.0 and 2.3 times faster on Native and on Wasm-GC, 1.4 and 1.5 times at 200 and 256 bits, 1.1 times at 512 bits and 1.05 at 2,048 bits on Native; Wasm-GC is unchanged at 256 and 512 bits and linear Wasm everywhere. The larger sizes are dominated by the division and squaring of the recursion, not by its base case. LLVM takes the Native settings, unmeasured because the toolchain used does not provide that backend. White-box tests compare the word kernels with the loops and with a BigInt oracle at every width from 1 to 256 bits (random, all ones, single bits, runs, the neighbours of exact squares near the extreme roots of each width). On Wasm (not on Wasm-GC) these roots still run the restoring loops: the word kernels are not enabled there and were not measured on that target.

The last stage of the 64-bit limb work moves the remaining coefficient kernels off the 32-bit view of the storage, so that only the 32-bit-limb routes of Wasm (multiplication, squaring and Knuth division on 32-bit limbs) use it, and every cutoff is named and documented in 64-bit limbs (bin_coeff_ntt_mul_min_words, bin_coeff_ntt_square_min_words, bin_coeff_toom3_min_words, bin_coeff_bz_division_min_words, bin_coeff_bz_leaf_words, bin_coeff_radix_format_dc_words, bin_coeff_sparse_min_words and the others of the threshold files, the same values halved). Converted: the multiplication and squaring dispatch, the unbalanced product (the block multiplication of the word Karatsuba replaces the BinCoeff-level one), the Burnikel–Ziegler recursion, the NTT digit conversion and overlap-add (the transforms keep their 32-bit Montgomery primes), the one-limb division, the sparse product, the bit operations, the byte and power-of-two radix conversions, the Lehmer threshold and the 256-bit square root kernel. The old divide-and-conquer root, its 512-bit kernel and the restoring loop are test-only references now. Retired instructions per operation on Native against the previous build: a sparse product of 8,192-bit operands 3.3 times fewer (4 and 12 nonzero limbs), bit_and plus bit_xor at 8,192 bits 2.8 times, a division by a one-limb divisor below 2322^{32} 2.2 times, from_bytes_be 1.2 times, and 1.00 to 1.09 times for the products, divisions, NTT products and gcd measured at 2,048 to 300,000 bits; nothing is slower. Results are unchanged: the regression digests recorded with the 32-bit implementation, the BigInt oracle tests, and new tests of the converted kernels against their 32-bit-limb definitions, the Knuth division, the schoolbook product and each other. The cutoffs keep their values (halved from limbs of 32 bits), except that LLVM now carries the cutoffs of the Native portable loops, not the values of the C and assembly rows of Native (its Burnikel–Ziegler cutoff is 96 limbs as on Wasm, against 208 on the Native portable loops), instead of an old copy of the Wasm ones; the elementary bit-burst precisions depend on multiplication cost, which this stage does not change. On Wasm and Wasm-GC the paired wall-clock runs of the radix conversion (in place against divide and conquer, 4,096 to 131,072 bits) put the parsing cutoff at 4,608 chunks as on Native (in place is 1.2 to 6.5 times faster up to 131,072 bits) and keep the formatting cutoff at 64 limbs (4,096 bits), above which divide and conquer is 1.2 to 3 times faster. The NTT digit conversion stays on the 32-bit view on Wasm and Wasm-GC (bin_coeff_ntt_limb32_conversion): with the 64-bit limb conversion a 300,000-bit product measured 0.88 times and a square 0.78 times as fast on Wasm-GC (seven paired runs each, outside the spread).

BinCoeff::to_radix_string and BinCoeff::parse in a radix that is not a power of two work on one limb array in place below their divide-and-conquer cutoffs. Formatting divides a copy of the 64-bit limbs by the chunk power (9 decimal digits, the largest power of the radix below 2322^{32}) one pass per chunk, and parsing accumulates value * chunk_power + chunk in place; each limb is two 32-bit halves with one 64 by 32 bit division or multiplication each, and the digits of a chunk are written into one string builder from a scratch array. Before, every chunk went through the 32-bit limb accessors and allocated a coefficient (about 113 instructions per 32-bit limb step against about 10 now). Chunks of 64 bits (19 decimal digits) are not used: a 128 by 64 bit quotient digit needs two hardware divisions where two 64 by 32 bit steps need one each, so by construction a pass over the limbs costs about the same per digit, and what was wrong was the per-chunk overhead, which is gone either way (not measured separately). The divide-and-conquer conversion starts at 6,144 32-bit limbs (196,608 bits) for formatting and at 4,608 chunks (about 41,000 digits) for parsing on Native and LLVM, measured as the crossover with retired instructions (formatting 65,536 bits 14.5 million against 25.5 million instructions for divide and conquer, 262,144 bits 220 million against 181 million; parsing 131,072 bits 47.2 against 48.3 million, 262,144 bits 201 against 146 million); Wasm and Wasm-GC keep the previous cutoffs of 128 limbs and 64 chunks until measured. Retired instructions per operation on Native, base 10, against the previous build: formatting 4.9, 5.7, 4.2 and 2.0 times fewer at 512, 2,048, 8,192 and 65,536 bits, parsing 6.1, 8.3, 4.7 and 1.5 times; base 16 (a power of two) is unchanged. White-box tests compare both paths with a chunk-by-chunk reference of the previous build for the radixes 3, 5, 7, 10, 12 and 36 at 1 to 513 limbs, with the values r9kr^{9k} and r9k−1r^{9k} - 1 around chunk edges up to 130 chunks, and with each other (in place against divide and conquer, formatting and parsing) on both sides of the old cutoffs.

Above 256 bits the integer square root on every target except JavaScript runs Zimmermann’s SqrtRem on word arrays instead of the BinCoeff divide-and-conquer root, which built about twenty-five temporaries per level (a BinCoeff operation on a few limbs costs 600 to 700 instructions, more than the division it surrounds). The radicand is shifted left by an even number of bits, below 128, to an even number nn of 64-bit limbs with the top two bits not both zero; each level cuts it into blocks of n/4n/4 limbs, takes the root and remainder of the upper part from the recursion, one division by twice that root and one squaring of the quotient through the coefficient dispatch, and corrects the root by at most one; a quotient of a whole block is capped one below, which is the root. The remainder of the original radicand comes back from the normalized one with a one-limb product, (r′+e(2s′−e))≫2t(r' + e(2s' - e)) \gg 2t with e=s′ mod 2te = s' \bmod 2^t for the shift 2t2t. The recursion ends in the fixed-width kernels at 256 bits. Retired instructions of one root on Native (release, radicand of twice the root width, paired with the previous build): 2.0 times fewer for a 512-bit root, 1.85 for 2,048 bits, 1.3 for 8,192 bits and 1.04 for 65,536 bits, where the division and the squaring of the recursion dominate; a root of 256 bits (a 512-bit radicand) 1.8 times. On Wasm-GC paired wall-clock runs of one root (radicand of twice the root width, medians of five) are 4.9 and 2.2 times faster at 512 and 2,048 bits and 1.3 and 1.07 times at 8,192 and 65,536 bits; on linear Wasm 2.2, 2.0, 1.4 and 1.05 times; on Native 2.0, 1.8, 1.3 and 1.05 times, in line with the instruction counts. No size is slower on any target, so the word recursion is selected on every target except JavaScript (the per-target constant bin_coeff_sqrt_array_enabled stays, and the previous recursion remains as the test reference). White-box tests compare it with the previous recursion, the restoring loop and a BigInt oracle from 129 to 4,097 bits (random, all ones, single bits, zero limbs inside the value, the neighbours of exact squares), and with the defining inequalities up to 33,000 bits.

Squaring on Native and LLVM no longer runs the half-product schoolbook (and, from 16,384 bits, the general product) up to the NTT: from 36 64-bit limbs (2,304 bits) a word-range Karatsuba square computes a02a_0^2, a12a_1^2 and (a0−a1)2(a_0 - a_1)^2 on array ranges, with the middle term a02+a12−(a0−a1)2a_0^2 + a_1^2 - (a_0 - a_1)^2 added in place, and the NTT square starts at 7,168 32-bit limbs (229,376 bits) instead of 768, because the Karatsuba square is cheaper up to there (retired instructions of one square: 12,288 bits 1.64 times fewer, 32,768 bits 2.2, 98,304 bits 1.7, 131,072 bits 1.09, 196,608 bits 1.18, equal from 262,144 bits). The Karatsuba multiplication of the word ranges now takes one scratch array per product, carved into the temporaries of each node, instead of five arrays and two copies per node: 1.02 to 1.04 times fewer instructions for a product of 2,048 to 65,536 bits, the same results. The schoolbook square stays below 36 limbs (the paired runs put the crossover between 32 and 40 limbs). Retired instructions per operation on Native, against the previous build: sqr 1.00, 1.00, 1.39 and 1.52 times fewer at 512, 2,048, 8,192 and 65,536 bits, mul 1.00, 1.02, 1.04 and 1.04 times, and the integer square root of a 65,536-bit root 1.23 times (its recursion squares). Wasm and Wasm-GC keep their squaring (bin_coeff_square_words_enabled is false there until paired wall-clock runs decide), and LLVM takes the Native values, unmeasured. White-box tests compare the scratch-buffer product with the allocating Karatsuba of the previous build and the schoolbook product at and around the cutoff with unbalanced shapes, the Karatsuba square with the schoolbook square and the product, and the dispatch against the schoolbook around 36, 64, 128, 256, 384 and 512 limbs and against the NTT and Karatsuba squares at the NTT cutoff.

Certified constants

The certified elementary functions memoize the constant enclosures they need (ln 2, ln 10 and pi) per working precision, in small per-constant caches of six precisions up to 65,536 bits. A cached enclosure is the value a recomputation returns, so results never depend on cache state or call order. Before this, every ln, log2, log10, sin, cos, tan and atan2 call re-ran an ln 2 series or an atan(1) evaluation that cost as much as the function itself. Paired native runs: ln 2.4 to 2.6 times faster at 53 to 512 bits, sin 2.4 to 3.7 times, decimal ln 2.5 times; on Wasm and Wasm-GC ln and sin are 1.7 to 2.2 times faster. exp has no such constant and is unchanged.

Measurement

The unified Maremark harness under bench/binary compares coefficient kernels, numeric cores, checked full paths, and semantically equivalent square candidates with balanced blocks. Auto-tune emits a versioned per-scale policy and applies a threshold only to the measured target; every threshold change still requires correctness tests on all targets.

The elementary release gate separately archives the immutable 0.6.1 commit and the dirty candidate tree, injects one identical add/mul/div/sqrt workload, and collects ten alternating AB/BA native pairs at 53, 128, and 512 bits. Maremark blocks release only when the candidate is at least 3% slower and the 95% bootstrap interval has a positive lower bound. Functions first introduced in 0.7.1 run as a candidate workload; this release becomes their first valid baseline, because inventing 0.6.1 timings for APIs that did not exist would be meaningless.

Certified series

The enclosure of exp evaluates its Taylor series once, not twice, when the argument is exact at the working precision (the usual case), because the lower and upper endpoints are then the same value and only one bound of each series is read. The trigonometric enclosure evaluates only the sine or cosine series that the requested function and quadrant read, two series instead of four for sin and cos. Both skips return the exact enclosures of before, which white-box tests check against copies of the previous code. Paired native runs: exp 1.8 to 2.0 times faster at 53 to 512 bits, decimal exp 1.3 to 1.4 times, sin 1.15 to 1.2 times on its own; on Wasm and Wasm-GC exp is 1.7 to 1.9 times faster.

Trade-offs

Schoolbook minimizes setup and allocation, recursive algorithms reduce asymptotic work, and NTT improves very large balanced inputs at the cost of transforms and temporary storage. Every fast path retains an exact fallback, so performance dispatch cannot alter semantics.

Fixed-point logarithm

The certified ln enclosure on the normalized argument in [1, 2] (and the ln 2 and ln 10 constants built from it) sums the series 2 * sum z^(2k+1) / (2k+1), z = (v - 1) / (v + 1), in fixed point when the argument is exact at the working precision. The fraction has 16 guard bits plus the leading zero bits of z, so the enclosure keeps precision + 16 significant bits even for an argument close to 1; every operation rounds down, which makes the sum a lower bound, and a proven error of less than 2 units per term and a tail bound give the upper bound. Arguments that are not exact, or so close to 1 that the fraction would exceed four times the working precision, use the previous floating-point series, so the refinement loop and its working precisions are unchanged. White-box tests check containment of a much tighter enclosure, a bound on the width, and equality of the final correctly rounded results and flags with those of the previous series. Paired runs without the constant cache: ln is 5 to 7 times faster on Native at 53 to 2,048 bits, 5.5 to 7.5 times on Wasm and Wasm-GC, and decimal ln 6 times.