python / python/cpython

bytes.fromhex() is 1.3 times slower than binascii.a2b_hex()

Open
#131,171 23 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

interpreter-core pending performance type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

I was looking at modernising some old code that uses binascii.a2b_hex, and I was surprised to find that bytes.fromhex() is a lot slower:

>>> timeit.timeit('bytes.fromhex("abcd1234abcd1234")', number=10000000)
1.0542256180197
>>> timeit.timeit('binascii.a2b_hex("abcd1234abcd1234")', 'import binascii', number=10000000)
0.4072963949292898

I thought maybe it was a difference in the lookup of the bytes classmethod vs the module lookup. It appears that it is, to some extent, but not completely:

>>> timeit.timeit('fromhex("abcd1234abcd1234")', 'fromhex=bytes.fromhex', number=10000000)
0.6133267850382254
>>> timeit.timeit('a2b_hex("abcd1234abcd1234")', 'from binascii import a2b_hex', number=10000000)
0.3788172130007297

Of course, all these times are extremely small, so it probably does not matter in most situations, but still, I found it surprising.

CPython versions tested on:

3.13

Operating systems tested on:

Linux

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the bytes.fromhex() and binascii.a2b_hex() timeit comparisons shown in the issue on CPython 3.13/Linux, then trace the two named entry points to understand the source of the difference. A useful result would identify whether bytes.fromhex() can be made faster and validate any change with equivalent benchmarks and relevant tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Needs clarification
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.