Skip to content

Optimize some predicate methods with attr_reader #5081

Open
@amomchilov

Description

@amomchilov

When I was tinkering around and profiling GraphQL Ruby around a year ago, I found some small+easy perf wins from optimizing some commonly queried "predicate methods", by defining them via attr_reader. I've lost the benchmarks, and don't have time to recreate them, but I still figured it's worth sharing the idea here.

Unfortunately, Ruby makes these unnecessarily ugly/difficult in the case of boolean attributes, but still possible with this method swizzling dance:

attr_reader :foo         # Define the fast method with a temporary name
alias_method :foo?, :foo # Give it a nice name
remove_method :foo       # Delete the temporary name

The main cuplrits were in type_kind.rb. I've opened a PoC PR here: #5082

Candidates for this kind of replacement can be found with these 2 regexes:

def ([a-z0-9_]+)\??[;\n]\s*@\1[;\n]\s*end
def ([a-z0-9_]+)\??\s*=\s*@\1

(They can be merged into one, but I opted not to, just to keep them somewhat legible)

Would you be able to take a quick stab at benchmarking these? And in general, do you think those perf wins are worth this ugliness?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions