rust-lang / rust-lang/rust

missed optimization: coalesce PathBuf reallocation

Open
#127,059 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

compare the following disassemblies:

#![allow(dead_code)]

use std::path::{Path, PathBuf};

#[no_mangle]
pub fn boxed_path() -> Box<Path> {
    Path::new("aaa").into()
}
boxed_path:
        lea     rdi, [rip + .L__unnamed_1]
        mov     esi, 3
        jmp     qword ptr [rip + std::path::<impl core::convert::From<&std::path::Path> for alloc::boxed::Box<std::path::Path>>::from::hfd2d6fbd02ea1491@GOTPCREL]

.L__unnamed_1:
        .zero   3,97
#![allow(dead_code)]

use std::path::{Path, PathBuf};

#[no_mangle]
pub fn boxed_path() -> Box<Path> {
    PathBuf::from("aaa").into()
}
boxed_path:
        push    rbx
        sub     rsp, 32
        lea     rsi, [rip + .L__unnamed_1]
        lea     rbx, [rsp + 8]
        mov     edx, 3
        mov     rdi, rbx
        call    qword ptr [rip + std::sys::os_str::bytes::Slice::to_owned::hda0e6bb365f52f1f@GOTPCREL]
        mov     rdi, rbx
        call    qword ptr [rip + std::ffi::os_str::OsString::into_boxed_os_str::haa190229882bb506@GOTPCREL]
        add     rsp, 32
        pop     rbx
        ret

.L__unnamed_1:
        .zero   3,97

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 two boxed_path examples and comparing their disassemblies, focusing on PathBuf::from("aaa").into() versus Path::new("aaa").into() and the Box<Path> conversion. Done means the PathBuf conversion no longer performs the unnecessary reallocation, with the generated assembly confirming the optimization.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.