🔍 Optimizing base64 decoding in jwt-cpp
jwt-cpp is a popular header-only C++ library for creating and verifying JSON Web Tokens. Clean, lightweight, no heavy dependencies — exactly the kind of lib you want in a Linux server stack.
While working with it I noticed a performance issue in the base64 decoding path. 🐛
⚙️ The old approach:
For every character in the input, the decoder called std::find_if to search linearly through a 64-char alphabet array.
→ O(n) per character lookup
→ Called for every single byte being decoded
→ A JWT with a large payload = a lot of unnecessary searching
🔧 The fix — a reverse lookup table:
Instead of searching, I precomputed a 256-entry lookup table. Each array index represents a byte value, each entry its base64 value — or -1 if invalid.
Decoding a character becomes a single array access:
auto index = rdata[static_cast<unsigned char>(symbol)];
→ O(1) per character lookup
→ No iteration, no comparisons
→ constexpr — lives in read-only memory, CPU cache friendly
📊 For JWT verification on a busy server this happens thousands of times per second. Small change, real impact.
👉 github.com/Thalhammer/jwt-cpp/commit/59cdb43
Subscribe to #jwt entries via RSS feed