Skip to content

Optimize generics to a dynamic dispatch for size #114598

@orowith2os

Description

@orowith2os

Generic currently generate two similar functions to do something - for some cases, this isn't desired, like in "all I care about is size" cases. For this, it seems reasonable for the compiler to instead check the input types at runtime and figure out what to do based off of that. I'm not quite sure how much it would help, but it would help nonetheless.

So, for a theoretical example:

fn convert_to_string<T: ToString>(input: T) -> String {
    input.to_string()
}

Given two inputs, an i32 and a f64 in this example, it would get turned into:

// The compiler will probably mangle these so they don't conflict, but that's a different topic
fn convert_to_string(input: i32) -> String {
    input.to_string()
}
fn convert_to_string(input: f64) -> String {
    input.to_string()
}

But, if the compiler were to be told to optimize it as much as possible for size, this would instead get turned into something like:

fn convert_to_string(input: i32 or f64) -> String {
    match typeof(input) {
        i32 => input.to_string(),
        f64 => input.to_string(),
    }
}

Obviously, the example code is a bit weird and isn't valid, but the idea is there. Instead of creating two different functions, make one that matches on the types at runtime. The point here is to work without traits, which is why I did not suggest converting generics that rely on traits to a dynamic dispatch instead.

This would also be useful with variadic generics, I think.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchI-heavyIssue: Problems and improvements with respect to binary size 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