by Ricardo “Rudxain” Fernández Serrata
Version 3 (May 16, 2024)
Download (89 downloads)
Multiplies text `n` times. Optimized for almost any value of `n`.
The subroutine is intended to be embedded in flows, that's why it has extra safety measures, to save resources (space, time, and energy), and for algorithmic correctness.
## Why/how it works:
0. For low `n`, it uses a loop-less "SIMD-like hack" that takes advantage of mostly-documented "quirks":
0.0. `join` converts an array of `null`s into a sequence of "null" strings. This is undocumented behavior!
0.1. Using `join` saves more memory than `++`, because there's no ", " delimiter.
0.2. "(?s)" is the dot-all regex flag, it avoids conditional branching, increasing performance. We use "...." instead of "null" for the same reason (branchless computation).
0.3. `replaceAll` will iterate over non-overlapping chunks of 4 chars, replacing each one by our input string, returning the desired result.
1. For high `n`, it switches to shift-&-add multiplication algorithm: https://2ality.com/2014/01/efficient-string-repeat.html
1.0. The constant `0xffff` is arbitrary. I haven't done any benchmarks to confirm if it's an optimal threshold.
Tags: multiply pad padding string
LICENSE: https://unlicense.org
Rudxain profile: llamalab.com/automate/community/flows/42921
5 stars | 2 | |
4 stars | 1 | |
3 stars | 0 | |
2 stars | 0 | |
1 star | 0 | |
Reports | 0 |
Rate and review within the app in the Community section.