Skip to content

str::contains is very slow for substring checks #25483

Closed
@netvl

Description

@netvl

Originally found in SO question.

This Rust code

fn main(){

    let needle   = (0..100).map(|_| "b").collect::<String>();
    let heystack = (0..100_000).map(|_| "a").collect::<String>();

    println!("Data ready.");

    for _ in 0..1_000_000 {
        if heystack.contains( &needle ) {
            // Stuff...
        }
    }

}

Executes for up to three minutes on my machine (even with -C opt-level=3), while the equivalent Ruby or Python code:

needle   = 'b' * 100
heystack = 'a' * 100_000

puts 'Data ready.'

1_000_000.times do
    heystack.include? needle
end

finishes in several seconds. Java variant finishes almost instantly (but that seems to be due to JIT optimizations).

It looks like that pattern searching for substrings could be severely optimized.

Metadata

Metadata

Assignees

No one assigned

    Labels

    I-slowIssue: Problems and improvements with respect to performance of generated code.P-mediumMedium priorityT-libs-apiRelevant to the library API 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