Skip to content
New issue

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

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

Already on GitHub? # to your account

Improve decoding performance by 40% by preallocating arrays of known length #2033

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

Conversation

adriancable
Copy link

Currently the generated .fromObject methods contain code like this:

                if (m.properties && m.properties.length) {
                    d.properties = [];
                    for (var j = 0; j < m.properties.length; ++j) {
                        d.properties[j] = $root.firebase.DeviceProperty.toObject(m.properties[j], o);
                    }
                }

This is bad, because you're doing m.properties.length allocations. We can do better since the size of the array is known:

                if (m.properties && m.properties.length) {
                    d.properties = Array(m.properties.length);
                    for (var j = 0; j < m.properties.length; ++j) {
                        d.properties[j] = $root.firebase.DeviceProperty.toObject(m.properties[j], o);
                    }
                }

This PR improves decode performance on the benchmark by around 40% (similar gains in the real world, too).

Before:

benchmarking decoding performance ...

protobuf.js (reflect) x 1,539,774 ops/sec ±4.99% (75 runs sampled)

After:

benchmarking decoding performance ...

protobuf.js (reflect) x 2,186,209 ops/sec ±1.41% (90 runs sampled)

itsfolf added a commit to UncollapseCo/protobuf.js that referenced this pull request Jan 20, 2025
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant