ASCII Validation from 2.5 to 114 GB/s with SIMD
I wanted to learn more about SIMD. The best camera programming language is the one that's with you that you know. For me that is Dart, and its SIMD support was incomplete, so I learned by contributing many missing pieces. ~100 PRs later, Dart's SIMD story is meaningfully better, and I know enough to write about it. Everything here works on Dart 3.14.
In this post, we take one small problem, ASCII validation, and rewrite it one step at a time, from a scalar loop to a vectorized one, and see how fast it gets. Each section is a single idea you can carry to other languages, and you don't even need real SIMD for those ideas to apply to your language, but more on that later.
Table of Contents
- What ASCII is
- What SIMD is
- The baseline
- Step 1: remove the branch
- Step 2: widen the load with SWAR
- Step 3: move to SIMD
- Step 4: the right per-vector test, anyTrue
- Step 5: hoist the constant
- Step 6: stop testing every vector
- Step 7: unroll the loop
- Step 8: remove the bounds checks
- Step 9: remove the interrupt checks
- Step 10: store the bytes as vectors
- The same steps on an older Intel machine
- The same steps in Flutter on an iPhone
- What's next
What ASCII is
Before you can build something, you need to understand it. Everyone agrees what ASCII is, but not everyone agrees what to do when something isn't ASCII.
Every ASCII character fits in seven bits, so a valid ASCII byte has its high bit clear. A byte is non-ASCII exactly when b & 0x80 is non-zero. Validating a buffer is asking that one question over every byte, and the whole post is about asking it faster. ASCII validation is worth optimizing because it is the fast path in UTF-8 decoding. In practice, you should use simdutf for UTF-8, but I'm getting ahead of myself. It's also a good warm-up. Your language might add overhead you don't see, such as bounds checks the compiler fails to eliminate, and starting with a format much simpler than UTF-8 shows you how much you can squeeze out of the language before the format itself gets in the way.
What happens when something is not ASCII? It's not that simple...
Everyone agrees on the bytes 0x00 to 0x7F. What a decoder labeled "ASCII" does with the bytes 0x80 to 0xFF is a different story, and it depends on who wrote the decoder:
- Strict US-ASCII: a high byte is an error. This is what RFC 20 and the IANA registry describe, and what Python's
asciicodec, Dart'sascii.decodeand Swift'sString(data:encoding: .ascii)do by default. - The WHATWG reading: in the WHATWG Encoding Standard, the label
asciiis an alias for windows-1252, so every byte decodes. In a browser,new TextDecoder('ascii').decode(Uint8Array.of(0x80))gives you€, not an error. - Microsoft's windows-1252: almost the same as the WHATWG one, except that the five bytes 0x81, 0x8D, 0x8F, 0x90 and 0x9D are unassigned and fail to decode, where WHATWG maps them to C1 control characters.
- Lossy decoders accept every byte and differ in what a high byte becomes. It turns into U+FFFD (Dart with
allowInvalid, Python witherrors="replace"), a question mark (.NET'sEncoding.ASCII), the byte with its high bit cleared (Buffer.toString('ascii')in Node, Bun and Deno turns 0xE9 intoi), the Latin-1 character with the same number (CFString and NSString), or nothing at all (iconv -c).
For the rest of this post, ASCII means the strict reading, where a byte is ASCII exactly when its high bit is clear.
What SIMD is
A normal instruction operates on one value. A SIMD instruction operates on a vector (aka list) of them, say four 32-bit integers at once, in a single wide register. This lets us solve some problems much faster. When a loop does the same thing to every byte, one SIMD instruction can do the work of sixteen ordinary ones, so the loop needs a fraction of the iterations and instructions to get through the same data.
We are going to write our SIMD code in Dart. Dart is a programming language like any other, and it has SIMD support in its standard library, where dart:typed_data exposes 128-bit vectors as types with lane-wise arithmetic, bitwise operations and comparisons. Everything here applies to other languages as well.
The vector types are:
Int32x4 // four 32-bit integer lanes
Float32x4 // four 32-bit float lanes
Float64x2 // two 64-bit float lanes
On the VM an Int32x4 lives in one 128-bit register, and bitwise operations like & and | compile to single hardware instructions.
The baseline
The simplest validator, which we'll call scalar, checks every byte and returns at the first one that isn't ASCII.
bool scalar(Uint8List b) {
for (var i = 0; i < b.length; i++) {
if (b[i] >= 0x80) return false;
}
return true;
}
Every iteration does one load of a single byte and one branch. The rest of the post is about touching more bytes per load and per instruction.

The charts in the steps come from an M3 MacBook Air, with the code compiled ahead of time. Each point is the fastest of five rounds of about 10 ms, after two warm-up rounds, in a fresh process for every buffer size. The charts use a build of Dart's main branch, and Dart 3.14.2 gives the same numbers within a few percent.
Step 1: remove the branch
Instead of testing every byte, OR every byte into an accumulator and check the high bit once at the end.
bool branchlessScalar(Uint8List b) {
var acc = 0;
for (var i = 0; i < b.length; i++) {
acc |= b[i];
}
return (acc & 0x80) == 0;
}

The branchless scalar version is only about 13 to 15% faster than scalar. With valid input the if is never taken. What the branchless form buys is that every byte goes through the same instructions, which the next steps build on.
Step 2: widen the load with SWAR
Before any vector types, there is a free trick called SWAR, SIMD Within A Register. Treat a plain 64-bit integer as eight byte lanes. Reinterpret the buffer as 64-bit words and OR whole words, so one load brings in eight bytes and one OR folds all eight.
bool swar(Uint8List b) {
var acc = 0;
if (b.length < 8) return branchlessScalar(b);
// A Uint64List view has to start at a multiple of 8 bytes.
final head = (-b.offsetInBytes) & 7;
for (var i = 0; i < head; i++) {
acc |= b[i];
}
final w = b.buffer.asUint64List(b.offsetInBytes + head, (b.length - head) >> 3);
for (var i = 0; i < w.length; i++) {
acc |= w[i];
}
for (var i = head + w.length * 8; i < b.length; i++) {
acc |= b[i];
}
return (acc & 0x8080808080808080) == 0;
}
A Uint64List view has to start at a multiple of eight bytes, so the bytes before that point go through a scalar loop first. >> 3 divides the rest by eight, which gives the number of whole 64-bit words, and the last few bytes that don't fill a word go through the loop at the end.

The mask widens to one 0x80 per lane. 17 GB/s from 4 KiB up, a 6x jump over branchless scalar for a few lines, with one eighth the loads and one eighth the loop iterations. This is the best effort to reward step in the post, and it uses no SIMD types at all.
Step 3: move to SIMD
As we've seen, SIMD lets us work on 128 bits at the same time (some SIMD instructions go wider). There is one problem. Dart doesn't have an Int8x16 type that would let us work on sixteen 8-bit integers at once. Dart does have Int32x4, which works on four 32-bit integers. And as we learned in Step 2, we can do SIMD within a register, so we can do SWAR within a SIMD register, with each 32-bit lane holding four of our bytes.
Reinterpret the buffer as an Int32x4List and work a vector at a time. As with SWAR, the view has to start at an aligned address, here a multiple of 16 bytes, and >> 4 counts only whole 16-byte vectors, so the bytes before and after them get scalar loops. The natural first attempt tests each vector and branches out on a non-ASCII byte.
final _hi = Int32x4.splat(0x80808080);
bool laneExtract(Uint8List b) {
if (b.length < 16) return branchlessScalar(b);
// An Int32x4List view has to start at a multiple of 16 bytes.
final head = (-b.offsetInBytes) & 15;
for (var i = 0; i < head; i++) {
if (b[i] >= 0x80) return false;
}
final v = b.buffer.asInt32x4List(b.offsetInBytes + head, (b.length - head) >> 4);
for (var i = 0; i < v.length; i++) {
final m = v[i] & _hi;
if ((m.x | m.y | m.z | m.w) != 0) return false;
}
for (var i = head + v.length * 16; i < b.length; i++) {
if (b[i] >= 0x80) return false;
}
return true;
}

About 13 GB/s from 16 KiB up. Slower than SWAR, despite touching twice as many bytes per iteration. Reaching for the vector type made things worse. The compiled loop shows why. Getting at the lanes takes four moves from the vector register into general-purpose registers, one for each of m.x to m.w, plus three ORs and a branch, all for a loop whose real work is one AND. It also reloads _hi on every iteration, which Step 5 deals with.
Step 4: the right per-vector test, anyTrue
What that loop wants is a single question. Did any lane survive the mask? A masked lane is non-zero exactly when one of its four bytes had the high bit set, so the operation we want is "is any lane non-zero". Dart did not have that reduction, so I added Int32x4.anyTrue, "true if at least one lane has any bit set".
bool anyTrueNoHoist(Uint8List b) {
if (b.length < 16) return branchlessScalar(b);
// An Int32x4List view has to start at a multiple of 16 bytes.
final head = (-b.offsetInBytes) & 15;
for (var i = 0; i < head; i++) {
if (b[i] >= 0x80) return false;
}
final v = b.buffer.asInt32x4List(b.offsetInBytes + head, (b.length - head) >> 4);
for (var i = 0; i < v.length; i++) {
if ((v[i] & _hi).anyTrue) return false;
}
for (var i = head + v.length * 16; i < b.length; i++) {
if (b[i] >= 0x80) return false;
}
return true;
}

About 15 GB/s from 16 KiB up. Only about 15% faster than the lane-extract version, which is the interesting part. The test is shorter now, about six instructions instead of the lane moves and ORs, and part of that only turns the result into a bool object before branching on it, which is suboptimal and will be optimized eventually. The bigger cost is still in the loop, and that is the next step.
Step 5: hoist the constant
_hi is a top-level final, so reading it is a static field load. A top-level final is initialized on first access, and its initializer could have side effects. Moving the load in front of the loop could run that initializer in a program that never reads _hi, so the VM plays it safe and doesn't move the load at all. So every iteration reloads the same constant vector from memory before it can do the AND. This can be fixed once SIMD types can be constants. Until then, the fix at the source level is one line that copies the constant into a local before the loop.
bool anyTrueHoist(Uint8List b) {
if (b.length < 16) return branchlessScalar(b);
// An Int32x4List view has to start at a multiple of 16 bytes.
final head = (-b.offsetInBytes) & 15;
for (var i = 0; i < head; i++) {
if (b[i] >= 0x80) return false;
}
final v = b.buffer.asInt32x4List(b.offsetInBytes + head, (b.length - head) >> 4);
final hi = _hi; // hoisted out of the loop by hand
for (var i = 0; i < v.length; i++) {
if ((v[i] & hi).anyTrue) return false;
}
for (var i = head + v.length * 16; i < b.length; i++) {
if (b[i] >= 0x80) return false;
}
return true;
}

About 28 GB/s from 16 KiB up. In the compiled loop, that reload costs eight extra instructions per iteration. Hoisting it nearly doubled the throughput, and once SIMD values can be constants the hand-hoist won't be needed.
Step 6: stop testing every vector
The branch tests every vector. We can instead OR every vector into an accumulator and ask the question once, after the loop. This is Step 1 again, where we remove the branch, this time from the vector loop.
bool accum(Uint8List b) {
if (b.length < 16) return branchlessScalar(b);
// An Int32x4List view has to start at a multiple of 16 bytes.
final head = (-b.offsetInBytes) & 15;
var tail = 0;
for (var j = 0; j < head; j++) {
tail |= b[j];
}
final v = b.buffer.asInt32x4List(b.offsetInBytes + head, (b.length - head) >> 4);
final hi = _hi;
var acc = Int32x4.zero();
for (var i = 0; i < v.length; i++) {
acc |= v[i];
}
for (var j = head + v.length * 16; j < b.length; j++) {
tail |= b[j];
}
return !(acc & hi).anyTrue && tail < 0x80;
}

About 30 GB/s, about 7% faster than the hoisted branch from 16 KiB up. On an all-ASCII buffer the branch is never taken. The reason to prefer this form is not the branch, it is that a single running accumulator is the shape that unrolls cleanly, which is the next step.
Step 7: unroll the loop
We can unroll the loop by eight vectors, so each iteration of the body handles 128 bytes instead of 16. We should also balance how the eight vectors are combined. Written as a chain, a0 | a1 | ... | a7, each OR waits on the previous one, a dependency chain seven deep. Written as a balanced tree, the depth drops to three, and the independent pairs can run at the same time, because modern processors execute instructions out of order, starting each one as soon as its inputs are ready rather than strictly in program order.
bool accumUnroll(Uint8List b) {
if (b.length < 16) return branchlessScalar(b);
// An Int32x4List view has to start at a multiple of 16 bytes.
final head = (-b.offsetInBytes) & 15;
var tail = 0;
for (var j = 0; j < head; j++) {
tail |= b[j];
}
final v = b.buffer.asInt32x4List(b.offsetInBytes + head, (b.length - head) >> 4);
final hi = _hi;
final n = v.length;
var acc = Int32x4.zero();
var i = 0;
for (; i + 8 <= n; i += 8) {
final t0 = v[i] | v[i + 1];
final t1 = v[i + 2] | v[i + 3];
final t2 = v[i + 4] | v[i + 5];
final t3 = v[i + 6] | v[i + 7];
acc |= (t0 | t1) | (t2 | t3);
}
for (; i < n; i++) {
acc |= v[i];
}
for (var j = head + v.length * 16; j < b.length; j++) {
tail |= b[j];
}
return !(acc & hi).anyTrue && tail < 0x80;
}

About 53 GB/s from 16 KiB up. Unrolling nearly doubled the throughput again. Balancing, on the other hand, did not help here. In a separate run, the same loop with a plain chain of eight ORs reached the same 54 GB/s at 64 MiB. The win in this loop comes from the unrolling.
Step 8: remove the bounds checks
Dart is a memory-safe language. An index like v[i] must lie between 0 and length - 1, or the access throws a RangeError instead of silently reading or writing memory it shouldn't, the kind of bug an unsafe language like C lets through. Unless the compiler can prove the index is always in range, it enforces this with a check, a compare and a branch on every access.
Unrolling introduced a cost that is easy to miss. In the single-index loop the optimizer proves i < length and drops the check. In the unrolled body it does not manage to prove i + 7 < length from the i + 8 <= n guard, so each of v[i] through v[i + 7] keeps its own check. In the compiled code, the simple loop of Step 6 has no bounds check left at all, while the unrolled body has eight.
Here the compiler is not capable enough yet to find that proof. Until then, a pragma tells it to skip the checks in this function when it is compiled ahead of time:
@pragma('vm:unsafe:no-bounds-checks')
bool accumUnrollUnsafe(Uint8List b) {
if (b.length < 16) return branchlessScalar(b);
// An Int32x4List view has to start at a multiple of 16 bytes.
final head = (-b.offsetInBytes) & 15;
var tail = 0;
for (var j = 0; j < head; j++) {
tail |= b[j];
}
final v = b.buffer.asInt32x4List(b.offsetInBytes + head, (b.length - head) >> 4);
final hi = _hi;
final n = v.length;
var acc = Int32x4.zero();
var i = 0;
for (; i + 8 <= n; i += 8) {
final t0 = v[i] | v[i + 1];
final t1 = v[i + 2] | v[i + 3];
final t2 = v[i + 4] | v[i + 5];
final t3 = v[i + 6] | v[i + 7];
acc |= (t0 | t1) | (t2 | t3);
}
for (; i < n; i++) {
acc |= v[i];
}
for (var j = head + v.length * 16; j < b.length; j++) {
tail |= b[j];
}
return !(acc & hi).anyTrue && tail < 0x80;
}

About 75 to 79 GB/s up to 64 KiB, while the buffer fits in the 128 KiB L1 data cache of the M3's performance cores, and about 66 GB/s from 256 KiB up. Removing the eight per-iteration checks buys about 48% while the data is in L1 and about 25% on large buffers. The pragma is a stopgap. The real fix is teaching bounds-check elimination to see through the unrolled indices, which is on my to-do list.
Step 9: remove the interrupt checks
The VM puts a check on every loop iteration so it can interrupt long-running code. It relies on that check for message delivery and GC scheduling, so it can't simply go away, but in a short, tight loop like this one we can drop it with another pragma, vm:unsafe:no-interrupts.
@pragma('vm:unsafe:no-bounds-checks')
@pragma('vm:unsafe:no-interrupts')
bool accumUnrollNoInterrupts(Uint8List b) {
if (b.length < 16) return branchlessScalar(b);
// An Int32x4List view has to start at a multiple of 16 bytes.
final head = (-b.offsetInBytes) & 15;
var tail = 0;
for (var j = 0; j < head; j++) {
tail |= b[j];
}
final v = b.buffer.asInt32x4List(b.offsetInBytes + head, (b.length - head) >> 4);
final hi = _hi;
final n = v.length;
var acc = Int32x4.zero();
var i = 0;
for (; i + 8 <= n; i += 8) {
final t0 = v[i] | v[i + 1];
final t1 = v[i + 2] | v[i + 3];
final t2 = v[i + 4] | v[i + 5];
final t3 = v[i + 6] | v[i + 7];
acc |= (t0 | t1) | (t2 | t3);
}
for (; i < n; i++) {
acc |= v[i];
}
for (var j = head + v.length * 16; j < b.length; j++) {
tail |= b[j];
}
return !(acc & hi).anyTrue && tail < 0x80;
}

About 82 GB/s at 64 KiB and about 70 GB/s beyond L1. That is about 5% faster than Step 8 at every size from 1 KiB up. A small win, but a free one.
Step 10: store the bytes as vectors
Every vector version so far viewed a Uint8List as an Int32x4List. You can instead store the data in a native Int32x4List and skip the view entirely. We keep everything from Step 9, including both pragmas.
@pragma('vm:unsafe:no-bounds-checks')
@pragma('vm:unsafe:no-interrupts')
bool accumUnrollNative(Int32x4List v) {
final hi = _hi;
final n = v.length;
var acc = Int32x4.zero();
var i = 0;
for (; i + 8 <= n; i += 8) {
final t0 = v[i] | v[i + 1];
final t1 = v[i + 2] | v[i + 3];
final t2 = v[i + 4] | v[i + 5];
final t3 = v[i + 6] | v[i + 7];
acc |= (t0 | t1) | (t2 | t3);
}
for (; i < n; i++) {
acc |= v[i];
}
return !(acc & hi).anyTrue;
}

About 107 to 114 GB/s while the data is in L1, the fastest version at every size and about 40% faster than Step 9. The view version reloads the view's data pointer for every vector and allocates the view on every call, and the native version does neither.
The same steps on an older Intel machine
To see how the steps carry over to x86, I ran the same code with Dart 3.14.2 stable on an Intel Core i5-4670K, a Haswell desktop processor from 2013, under Ubuntu.

The order mostly holds. Step 10 reaches about 40 GB/s at 64 KiB, roughly 21x the scalar baseline. Steps 3 to 5 stay below SWAR here, and Step 9 brings no gain over Step 8.
The same steps in Flutter on an iPhone
Everything above is plain Dart, so it also runs in Flutter. I put the eleven versions into a small Flutter app and ran it in release mode on an iPhone 15 Pro. The app draws its own chart:

The phone lands close to the M3. Step 10 peaks at about 114 GB/s at 64 KiB, the same as on the laptop, and every step keeps its place in the order. Step 9 is ahead of Step 8 at most sizes here too, as on the M3.
What's next
These ten steps are as far as I could take this loop in Dart today. There is still some performance left. The good news is that I already know what it takes to get there, and I'm working on the compiler and library changes it needs. I hope they land soon, and that a future version of this post can end at full speed.
Validation is also only half of decoding. Turning the bytes into a String is the other half, and that is where the next post will probably pick up. Fast byte handling only pays off if the bytes arrive fast too, which I learned the hard way with a lexer.
I'm grateful to the people who helped me land the SDK changes behind this post. Kevin Moore helped me give the work a clear direction and make it visible, Martin Kustermann and Slava Egorov reviewed most of them, and Lasse Nielsen, Alexander Markov and Stephen Adams helped with reviews and advice on the APIs. Thanks also to everyone else who reviewed a change along the way.