Skip to content

perf: use native toHex in bytesToHex and skip TextEncoder for short ASCII strings - #5534

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

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

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

  • bytesToHex uses the native Uint8Array.prototype.toHex (Node 25+, Chrome 140+, Firefox 133+, Safari 18.2+), found once at module load. Other runtimes, plain arrays, cross-realm arrays and empty views keep the existing table loop. Empty views matter: a detached or out-of-bounds view has length 0 and native toHex throws on it, while the loop returns 0x.
  • stringToBytes skips TextEncoder for ASCII strings of up to 64 characters, since their char codes are already the UTF-8 bytes. TextEncoder.encode costs about 1µs per call in V8, and arrays of up to 64 bytes are allocated on the heap. Longer or non-ASCII strings go through TextEncoder as before.
  • stringToHex is now bytesToHex(stringToBytes(value), opts), so it gets both changes. toHex.ts now imports from toBytes.ts, which already imports from toHex.ts; the cycle is safe because neither module calls the other at load time, and fromHex.ts and toBytes.ts already import each other the same way.

Output is also a flat string instead of a rope: a 32-byte hash now retains about 120 bytes instead of about 1 KB.

Behavior

Unchanged. A harness compared main and this branch on 103,377 calls across bytesToHex, stringToHex, stringToBytes, toHex, toBytes, keccak256, checksumAddress and the rest of the encoding and data utils, on Node 26 (native toHex), Node 24 (no native toHex) and Bun 1.4. Return values (including the Uint8Array constructor) and thrown errors (class and message) were identical in every case. Inputs included every byte value, subarray views, Buffer, detached and out-of-bounds views, length-tracking views, plain arrays, lone surrogates, non-ASCII at the 64-character boundary, and the size option.

New tests pin the cases a plausible regression would break: every byte value, views and Buffer against an independent encoding, a detached buffer (fails if the length guard is removed), and ASCII and non-ASCII strings around 64 characters against Buffer.from(value, 'utf8').

CI runs Node 24, which has no native toHex, so CI covers only the fallback branch. I ran the encoding, data, hash and address tests on Node 26 as well.

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/toHex.bench.ts:

Bench main (ops/s) branch (ops/s) ×
bytesToHex 20 B, random pool 3,550,229 6,635,706 1.87
bytesToHex 32 B, random pool 2,981,706 5,657,550 1.90
bytesToHex 1 KB, random pool 120,180 554,880 4.62
bytesToHex 100 KB, random pool 1,250 6,453 5.16
bytesToHex 1 KB (existing bench) 119,479 222,577 1.86
stringToHex('Hello world.') 920,643 4,281,345 4.65
stringToHex, 64 chars 760,885 2,087,822 2.74
stringToHex, 200 chars 374,165 519,343 1.39
stringToHex, 10K chars 12,657 52,489 4.15
stringToHex, 12 chars non-ASCII 908,990 872,139 0.96 (unchanged path)

src/utils/address/getAddress.bench.ts, uncached checksum (20,000 distinct addresses, more than the 8,192-entry cache): 46,040 → 50,739 (1.10×). keccak dominates this path, so the stringToBytes saving barely shows.

stringToBytes (standalone loop, not in a bench file, to keep this PR's bench edits away from the hexToBytes PR):

Input main (ops/s) branch (ops/s)
'Hello world.' 1,144,655 11,841,879
40 hex chars 1,014,605 3,652,996
'transfer(address,uint256)' 1,002,657 4,388,372
64 chars 911,060 2,880,267
100 chars (unchanged path) 869,613 863,654

Node 24 (no native toHex, so only the ASCII change applies): bytesToHex stays within noise (0.99–1.03× on the random pools), stringToHex('Hello world.') is 2.45× and 64 chars 1.53×, and the 10K-char and non-ASCII cases are unchanged (1.08×, 0.94×).

Bytes allocated per call (node --expose-gc, large young generation):

Case main branch
bytesToHex 32 B 1,003 121
bytesToHex 1 KB 5,958 2,167
bytesToHex 100 KB 655,642 204,922
stringToHex('Hello world.') 577 444

Size

Entry main this PR all five PRs limit
import * from 'viem' (esm) 91,183 B 91,384 B (+201) 91,881 B (+698) 92 kB
const viem = require('viem') (cjs) 117,921 B 117,925 B (+4) 118,541 B (+620) 118.5 kB → 119 kB
import * from 'viem/account-abstraction' 61,497 B 61,706 B (+209) 62,072 B (+575) 62 kB → 62.5 kB
import { privateKeyToAccount } from 'viem/accounts' 21,696 B 21,784 B (+88) 22,122 B (+426) 22 kB → 22.5 kB
import * from 'viem/actions' 72,912 B 72,990 B (+78) 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/data src/utils/hash src/utils/address src/utils/unit: passing on Node 26.
  • 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). On Node 24, which CI runs, the native toHex branch can't run, so it shows as uncovered there; the fallback loop is covered on both through a Uint8Array from another realm (node:vm).
  • Biome clean; tsc clean for src and the changed test and bench files.
  • pnpm knip --production clean on the five PRs merged together.

@changeset-bot

changeset-bot Bot commented Nov 16, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 29b3a77

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

@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:01am UTC

Request Review

@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-16T01:59:17.093561Z 29b3a77 PR opened
ℹ️ 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.

@github-actions

Copy link
Copy Markdown
Contributor

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

pnpm add viem@pr-5534
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 — 29b3a773 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