Skip to content

perf: add fast paths to numberToHex, hexToNumber, hexToBigInt, bytesToNumber and bytesToBigInt - #5536

Closed
jxom wants to merge 3 commits into
mainfrom
perf/number-encoding
Closed

jxom wants to merge 3 commits into
mainfrom
perf/number-encoding

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

Fast paths for the common cases. Each one falls through to the existing code for anything it does not handle, so errors come from the same code as before.

  • numberToHex: an unsigned safe integer or non-negative bigint fits size bytes exactly when its hex has at most size * 2 digits. The fast path checks that with toString(16).padStart, without the bigint bound math. Signed values, out-of-range values and unusual sizes take the existing path.
  • hexToNumber: when unsigned, unsized and 0x-prefixed, Number(hex) parses it directly, and a safe-integer result is exact. Anything else, including unsafe results, goes through hexToBigInt and the existing range error.
  • hexToBigInt (signed, negative): BigInt.asIntN instead of building an f…f string and parsing it. This applies only to 0x input, which always fits size bytes. Input without the prefix is parsed as decimal by BigInt, so it keeps the old arithmetic.
  • bytesToNumber / bytesToBigInt: when unsigned and non-empty, skip leading zero bytes and, with up to 6 significant bytes (always a safe integer), accumulate the value directly instead of going through hex. This is the ABI offset and length word case.

Behavior

Unchanged. A harness compared main and this branch on 103,377 calls on Node 26, Node 24 and Bun 1.4: identical return values and identical thrown errors (class and message). Inputs included the 2^53 boundary from both sides, -0, NaN, Infinity, fractions, 2n ** 256n at size: 32, signed min/max for sizes 1, 2 and 32, size of 0, -1, 1.5, '32', NaN and Infinity, hex with trailing whitespace, 0X, _, missing prefix, empty bytes, 6 and 7 significant bytes, and non-string or non-array junk.

New tests snapshot (recorded on main) numberToHex, hexToNumber, hexToBigInt, bytesToNumber and bytesToBigInt across those boundaries, including the error messages.

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.

Bench main (ops/s) branch (ops/s) ×
numberToHex(52) 5,191,993 9,069,122 1.75
numberToHex(420, { size: 32 }) 2,245,128 5,065,121 2.26
numberToHex(uint256, { size: 32 }) 2,045,788 3,557,092 1.74
hexToNumber('0x1a4') 6,108,946 12,603,092 2.06
hexToBigInt(negative 32 B, { signed: true }) 800,334 1,276,424 1.59
bytesToNumber(32 B offset word) 1,463,031 9,183,825 6.28
bytesToBigInt(32 B offset word) 1,644,639 7,603,149 4.62
bytesToBigInt(32 B uint256) 1,440,586 1,382,252 0.96 (unchanged path)

Benches are in toHex.bench.ts, fromHex.bench.ts (the hexToNumber bench is no longer skipped) and fromBytes.bench.ts.

Bytes allocated per call: numberToHex(420, { size: 32 }) 596 → 376, numberToHex(uint256, { size: 32 }) 504 → 224, bytesToNumber(offset word) 1,123 → 56, bytesToBigInt(offset word) 1,123 → 80.

Size

Entry main this PR all five PRs limit
import * from 'viem' (esm) 91,183 B 91,435 B (+252) 91,881 B (+698) 92 kB
const viem = require('viem') (cjs) 117,921 B 118,134 B (+213) 118,541 B (+620) 118.5 kB → 119 kB
import * from 'viem/account-abstraction' 61,497 B 61,727 B (+230) 62,072 B (+575) 62 kB → 62.5 kB
import { privateKeyToAccount } from 'viem/accounts' 21,696 B 21,802 B (+106) 22,122 B (+426) 22 kB → 22.5 kB
import * from 'viem/actions' 72,912 B 72,980 B (+68) 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: 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:09am UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: eb36113

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:30.782804Z eb36113 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: dee4a5aedc

ℹ️ 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/encoding/fromHex.test.ts Outdated
Comment on lines +3 to +4
import type { BaseError } from '../../errors/base.js'
import type { Hex } from '../../types/misc.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 public test types through the package entrypoint

Root AGENTS.md explicitly requires tests to import public APIs through package entrypoints rather than relative source paths. Both BaseError and Hex are public exports, so these newly added imports violate that repository convention. Import them from 'viem' instead, and apply the same correction to the new BaseError imports in fromBytes.test.ts and toHex.test.ts.

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 eb36113: Hex now comes from viem. The edge-case helpers no longer need BaseError; they read the first line of error.message, which gives the same snapshots. #5537 also moved its new Hex imports to viem.

@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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

pnpm add viem@pr-5536
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 — eb361139 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