rust-lang / rust-lang/rust

Matching on `str.chars().next()` is slower than matching on `str.bytes().next()`

Open
#127,666 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-optimization I-slow S-has-mcve T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:
https://godbolt.org/z/8c74Yzfoj

pub fn src(s: &str) -> u32 {
    match s.chars().next() {
        None => 0,
        Some('a') => 1,
        Some('b') => 2,
        Some(_) => 3,
    }
}

pub fn tgt(s: &str) -> u32 {
    match s.bytes().next() {
        None => 0,
        Some(b'a') => 1,
        Some(b'b') => 2,
        Some(_) => 3,
    }
}

I expected to see this happen:
The assembly generated for src should be identical to that of tgt.

Instead, this happened:
The assembly generated for src contains branches checking for 2, 3 or 4 byte long encodings of the 'a' or 'b' characters. These encodings will never actually occur in str, since UTF-8 must always use the shortest encoding of any character. I think such information could be communicated to LLVM through some assumes.

Meta

rustc --version --verbose:

rustc 1.81.0-nightly (0c81f94b9 2024-07-10)
binary: rustc
commit-hash: 0c81f94b9a6207fb1fc080caa83584dea2d71fc6
commit-date: 2024-07-10
host: x86_64-unknown-linux-gnu
release: 1.81.0-nightly
LLVM version: 18.1.7

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 src and tgt comparison from the linked Godbolt example with the reported nightly rustc version, then inspect how Rust and LLVM represent str.chars().next() versus str.bytes().next(). Done means the generated assembly no longer checks impossible multi-byte encodings for ASCII matches, with a regression test or reproducible validation covering the behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers, performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.