Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Memoize instances typcasters in typecaster map #152

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

film42
Copy link

@film42 film42 commented Feb 8, 2016

All of the default typecasters are stateless, so allocating a new instance for each field becomes extremely costly, especially for larger models. To reduce this, we can memoize the TYPECASTER_MAP.

This should be a backwards compatible change with a speed boost. The only people who might have trouble are those who modified the typecaster map. This is a frozen constant, though, so nobody should be touching this.

This is currently about 10% quicker on a model with 93 fields. The benchmark creates a model and then calls to_json. I also ran the benchmark on a smaller model with only 12 String fields and saw a 1-2% improvement.

#
# @since 0.6.0
def typecaster_for(type)
typecaster = TYPECASTER_MAP[type]
typecaster.new if typecaster
typecaster if typecaster
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This final line is no longer necessary since you're not calling anything. The method simply becomes:

def typecaster_for(type)
    TYPECASTER_MAP[type]
end

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💥 Thanks for catching that!

All of the default typecasters are stateless by default, so allocating
a new instance for each field becomes extremely costly, especially for
larger models. To reduce this, we memoize instances by default, but
still allow users to provide a custom stateful type.
@fxfilmxf
Copy link

fxfilmxf commented Jul 7, 2016

+1 I was just about to open a PR with the exact same change!

@film42
Copy link
Author

film42 commented May 15, 2017

🤖 Beep boop! Just sending a ping ❤️😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants