rust-lang / rust-lang/rust

Creating an array can be made 2x faster

Open
#139,875 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-LLVM C-optimization I-heavy T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Consider this simple function:

const SIZE: usize = 4096;

fn array_of_twos() -> [u64; SIZE] {
    [2; SIZE]
}

Because 2u64 doesn't have the same bytes throughout, the compile can't call memset and instead creates a vectorized loop.

However, from my testing, using the rep stosq instruction is over twice as fast for large arrays (more than a few hundred elements). Here is a faster version of the same function:

fn array_of_twos_faster() -> [u64; SIZE] {
    let mut arr = MaybeUninit::uninit();
    unsafe {
        asm!(
            "mov rax, 2",
            "mov rcx, {}",
            "mov rdi, {}",
            "rep stosq",
            const SIZE,
            in(reg) arr.as_mut_ptr(),
            lateout("rax") _, lateout("rdi") _, lateout("rcx") _,
            options(nostack, preserves_flags)
        );
        arr.assume_init()
    }
}

Benchmarking both with Criterion:

normal                  time:   [1.5435 µs 1.5465 µs 1.5501 µs]
                        change: [-3.1683% -2.2863% -1.4243%] (p = 0.00 < 0.05)
                        Performance has improved.
Found 4 outliers among 100 measurements (4.00%)
  2 (2.00%) high mild
  2 (2.00%) high severe

rep stosq               time:   [633.94 ns 636.36 ns 639.77 ns]
                        change: [-2.2975% -1.8986% -1.4693%] (p = 0.00 < 0.05)
                        Performance has improved.
Found 9 outliers among 100 measurements (9.00%)
  4 (4.00%) high mild
  5 (5.00%) high severe

Compare both of them on Godbolt.

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 array_of_twos and array_of_twos_faster examples and comparing their generated code on the linked Godbolt page. Run the Criterion benchmark described in the issue to verify the performance difference. Done means the compiler produces a faster implementation for large repeated u64 arrays without requiring the manual unsafe asm version.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers, performance
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.