Skip to content

Memoize instances typcasters in typecaster map#152

Open
film42 wants to merge 1 commit intocgriego:masterfrom
film42:gt/optimize_typing
Open

Memoize instances typcasters in typecaster map#152
film42 wants to merge 1 commit intocgriego:masterfrom
film42:gt/optimize_typing

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.

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.
@film42 film42 force-pushed the gt/optimize_typing branch from f4ccaa1 to bbf20e7 Compare February 9, 2016 04:30
@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

Comments