Skip to content

String::new() is slower than "".to_string()  #86106

Description

I tried this code:

pub fn a() -> String {
    String::new()
}

pub fn b() -> String {
    "".to_string()
}

I expected to see this happen: both functions contain identical code.

Instead, this happened: https://rust.godbolt.org/z/P53MMG4W6.

For String::new() it does one more instruction: mov rcx, qword ptr [rip + .L__unnamed_1]. This rcx is then read further below at mov qword ptr [rdi], rcx.
The "".to_string() version however does not do this extra step and immediately reads from a constant: mov qword ptr [rdi], 1.
This means that String::new() does slightly more work than "".to_string() but I expect them to be identical.

Before 1.52.0 the functions generated identical code: https://rust.godbolt.org/z/8647E6YhY.

oli noted the following:

The problem is probably because it copies its value from the constant

pub const NEW: Self = Self::new();
instead of immediately creating the appropriate value

Meta

This currently happens on nightly.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-bugCategory: This is a bug.E-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.I-slowIssue: Problems and improvements with respect to performance of generated code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions