A Very Fast IPv4 Parser, in Swift
In a recent blog post, a new fast IPv4 parser was introduced, written in Swift and designed to achieve impressive performance on modern processors. The post explains that the parser can parse an IPv4 address in just 15 CPU cycles, with a throughput of 75 instructions on an M6 processor, resulting in a processing time of around 3 nanoseconds.
One of the key challenges in creating a fast IPv4 parser is the need for high parallelism in the CPU, allowing it to perform multiple calculations simultaneously. To achieve this, the algorithm utilizes two main techniques. The first technique takes advantage of the fact that, while the exact position of each segment in an IPv4 address is unknown, we do know their approximate locations. For example, the first segment and its following dot must always be within the first 4 characters of the string.
The second technique employs clever bit hacks, specifically using Single-Instruction Multiple-Data (SIMD) techniques. Modern processors often have 64-bit wide general-purpose registers, which means that operations performed on these registers are highly efficient. By cramming multiple UInt8 values into a single UInt64 register, the CPU can perform operations on all the values simultaneously, rather than sequentially. This optimization significantly improves the performance of the parser.
The algorithm is designed to exploit the fact that valid IPv4 addresses cannot be shorter than 7 characters. Using this knowledge, the parser can quickly identify the position of the dots separating the segments and parse the digits accordingly. By using multiple "windows" to process the address simultaneously, the algorithm enables the CPU cores to execute multiple arithmetic operations in a single cycle, resulting in high instruction-level parallelism.
The final implementation of the parser, which includes detailed documentation comments and passes Swift's extensive test suite as well as some fuzz-tests, is available online. This new IPv4 parser implemented in Swift demonstrates a significant improvement in performance compared to existing implementations, making it a valuable addition to the Swift networking ecosystem.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.