Skip to content

perf: decode hex through a nibble table in hexToBytes and in one pass in toBytes - #5535

Closed
jxom wants to merge 3 commits into
mainfrom
perf/hex-to-bytes
Closed

jxom wants to merge 3 commits into
mainfrom
perf/hex-to-bytes

Conversation

@jxom

@jxom jxom commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

From the sync encoding primitives section of a performance and memory audit. Every change keeps outputs and errors identical; see Behavior.

Summary

  • hexToBytes decodes through a 128-entry Int8Array nibble table and writes straight into the output, including the size right-padding, with no intermediate slice/padEnd strings. On a non-hex character it reruns the existing loop, so the thrown error is the same. Unusual sizes (NaN, fractions, negatives) and inputs shorter than 2 characters also take the existing loop.
  • toBytes decodes 0x strings in one pass instead of running the isHex regex and then decoding. Sized calls and strings that fail to decode take the existing isHex path, so '0xzz' still encodes as UTF-8. keccak256 and numberToBytes go through these functions and inherit the change.

Native Uint8Array.fromHex / setFromHex were measured and lose to the table on V8 at every size (32 B: 2.12M vs 3.46M ops/s; 100 KB: 1,125 vs 1,692), so this does not use them.

Behavior

Unchanged for every input of the declared types. A harness compared main and this branch on 103,377 calls (hexToBytes, toBytes, fromHex, numberToBytes, keccak256 and the rest of the encoding and data utils) on Node 26, Node 24 and Bun 1.4: identical return values and identical thrown errors (class and message). Inputs included every byte value in both cases, odd lengths, '', '0x', strings without a 0x prefix, 0X, characters on either side of each hex range (/ : @ G \ g), non-ASCII characters whose low byte looks like a hex digit (İ, ı), whitespace, a bad character at a random position, and the sizeoption including0, negatives, fractions and NaN`.

One difference outside realistic use: a size above V8's maximum string length divided by two (about 256 MiB) used to throw RangeError: Invalid string length from padEnd. It now allocates the array, or throws the engine's allocation RangeError when that fails.

New tests pin every byte value in mixed case against Buffer.from(hex, 'hex'), the error message for characters next to the hex ranges, for non-ASCII characters, after uppercase digits and with size (all of which go through the old loop), the behavior of skipping the first two characters without checking them, toBytes encoding non-hex 0x strings as UTF-8, and keccak256('0xzz') hashing the UTF-8 text. The snapshots were recorded on main and pass unchanged here.

Benchmarks

SKIP_GLOBAL_SETUP=true vitest bench --project core --run <file>, Node 26.13, same bench file on main and this branch. The orb is shared, so expect ±10–20% noise.

src/utils/encoding/toBytes.bench.ts (random pools are flat strings, like parsed JSON-RPC responses):

Bench main (ops/s) branch (ops/s) ×
hexToBytes 20 B, random pool 1,621,649 4,095,735 2.53
hexToBytes 32 B, random pool 1,288,205 3,067,156 2.38
hexToBytes 1 KB, random pool 54,471 145,523 2.67
hexToBytes 100 KB, random pool 540 1,570 2.91
hexToBytes 1 KB (existing bench) 89,164 115,387 1.29
hexToBytes 20 B, size: 32 1,520,058 1,712,749 1.13
toBytes 32 B hex 1,896,458 4,522,943 2.38

The size: 32 row is low because of JIT state left by the benches before it in the same file: in a standalone loop the same call goes 1.51M → 7.86M ops/s.

src/utils/hash/keccak256.bench.ts: unchanged within noise (32 B hex 78,664 → 77,056; 1 KB hex 10,947 → 11,334). The hash itself takes about 12µs, so saving a few hundred nanoseconds of decoding does not show. It's included as a baseline for the @noble/hashes question.

Bytes allocated per call: hexToBytes 32 B 284 → 253, toBytes 32 B hex 392 → 304. Larger inputs are dominated by the output array.

Size

Entry main this PR all five PRs limit
import * from 'viem' (esm) 91,183 B 91,511 B (+328) 91,881 B (+698) 92 kB
const viem = require('viem') (cjs) 117,921 B 118,133 B (+212) 118,541 B (+620) 118.5 kB → 119 kB
import * from 'viem/account-abstraction' 61,497 B 61,790 B (+293) 62,072 B (+575) 62 kB → 62.5 kB
import { privateKeyToAccount } from 'viem/accounts' 21,696 B 21,902 B (+206) 22,122 B (+426) 22 kB → 22.5 kB
import * from 'viem/actions' 72,912 B 73,070 B (+158) 73,494 B (+582) 73.5 kB → 74 kB

This PR fits the current limits on its own (pnpm size with time measurement off, since there's no Chrome here). All five PRs in this series together go over three limits by 41–122 B and leave viem/actions 6 B under its limit. So every PR in the series raises those four limits by 0.5 kB in a separate chore: commit (precedent: 9677703). The edit is identical in each PR, so git merges them cleanly in any order, and no intermediate merge state breaks pnpm size.

Series: #5534 (bytesToHex, stringToHex, stringToBytes), #5535 (hexToBytes, toBytes), #5536 (number conversions), #5537 (data utils), #5538 (TextDecoder, normalizeSignature, formatUnits). They touch some of the same files in separate hunks; any merge order applies cleanly (checked both orders).

Checks

  • Equivalence harness (main vs branch): 103,377 calls, 0 differences on Node 26, Node 24 and Bun.
  • pnpm test --project core --run src/utils/encoding src/utils/hash: passing.
  • src/utils, src/accounts, src/siwe: the only failures are the Anvil-dependent tests that fail identically on main here (no Anvil in this environment).
  • Line and branch coverage of the changed modules on Node 26 is the same as on main: full, apart from two branches that were already uncovered (slice.ts L67, Value.ts L29).
  • Biome clean; tsc clean for src and the changed test and bench files.
  • pnpm knip --production clean on the five PRs merged together.

@vercel

vercel Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
viem Error Error Nov 16, 2026 2:10am UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 2288b8f

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
viem Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-16T02:07:43.104261Z 2288b8f New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8668bfee5d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/utils/hash/keccak256.test.ts Outdated
@@ -1,5 +1,6 @@
import { expect, test } from 'vitest'

import { stringToBytes } from '../encoding/toBytes.js'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Import the public test helper through the package entrypoint

The new stringToBytes import bypasses the package entrypoint even though this function is publicly exported from viem. The root AGENTS.md explicitly requires package-entrypoint imports for public surface tests; importing the implementation directly leaves that wiring outside the regression test. Import stringToBytes from 'viem' instead.

AGENTS.md reference: AGENTS.md:L188-L190

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2288b8f: keccak256.test.ts now imports stringToBytes from viem, and the new Hex/BaseError type imports in toBytes.test.ts come from viem too.

@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Published [email protected] under the pr-5535 dist-tag, which follows this pull request until it closes.

pnpm add viem@pr-5535
pnpm add [email protected]

jxom commented Nov 16, 2026

Copy link
Copy Markdown
Member Author

Bundled into #5543 as its own commit, so this PR is superseded. Closing in favour of the bundle.

@jxom jxom closed this Nov 16, 2026

This branch had an error being deployed

1 failed deployment
Preview — 2288b8fe Deployed Nov 16, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants