protobuf icon indicating copy to clipboard operation
protobuf copied to clipboard

Ruby: Use class inheritance to save memory

Open casperisfine opened this issue 3 years ago • 3 comments

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 avatar Jul 20 '22 09:07 casperisfine

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.

haberman avatar Aug 09 '22 23:08 haberman

I can make that constant private.

casperisfine avatar Aug 10 '22 08:08 casperisfine

Done:

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

casperisfine avatar Aug 10 '22 08:08 casperisfine