Skip to content

Ruby: Use class inheritance to save memory#10281

Merged
deannagarcia merged 1 commit intoprotocolbuffers:mainfrom
casperisfine:ruby-smaller-message-classes
Aug 12, 2022
Merged

Ruby: Use class inheritance to save memory#10281
deannagarcia merged 1 commit intoprotocolbuffers:mainfrom
casperisfine:ruby-smaller-message-classes

Conversation

@casperisfine
Copy link
Contributor

The only difference between all the Message classes is just their descriptor instance variable.

So rather than create an entirely new class from scratch every time we can simply inherit from an abstract class.

This shink each Message class from 1456 bytes to 944 bytes, and the singleton class of each from 960 to 792, for a total of 680 bytes saved per message class, so a ~28% reduction.

@haberman
Copy link
Member

haberman commented Aug 9, 2022

I wish there was a way to do this that didn't affect the public API.

If we do this, developers can start writing:

if obj.kind_of? Google::Protobuf::AbstractMessage
  # This is a protobuf
end

That might not be the worst thing, but it would commit us to maintaining this inheritance hierarchy.

@casperisfine
Copy link
Contributor Author

I can make that constant private.

The only difference between all the `Message` classes is just
their `descriptor` instance variable.

So rather than create an entirely new class from scratch every time
we can simply inherit from an abstract class.

This shink each `Message` class from `1456` bytes to `944` bytes, and
the singleton class of each from `960` to `792`, for a total of
`680` bytes saved per message class, so a ~28% reduction.
@casperisfine casperisfine force-pushed the ruby-smaller-message-classes branch from 6c5cacb to 7309e88 Compare August 10, 2022 08:38
@casperisfine
Copy link
Contributor Author

Done:

>> require 'google/protobuf'
=> true
>> Google::Protobuf::AbstractMessage
(irb):2:in `<main>': private constant Google::Protobuf::AbstractMessage referenced (NameError)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants