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

Improve Packet.read_byte performance #134

Merged
merged 1 commit into from
Mar 8, 2021
Merged

Conversation

tenderlove
Copy link
Contributor

Packet.read_byte reads a byte from the socket and returns it. Before
this commit it would allocate a string and an array, after this commit
it makes 0 allocations.

Here is a benchmark:

require "mqtt/packet"

def count_alloc
  x = GC.stat(:total_allocated_objects)
  yield
  GC.stat(:total_allocated_objects) - x
end

File.open(__FILE__) do |f|
  10.times do
    allocations = count_alloc do
      MQTT::Packet.read_byte f
    end

    p ALLOCATIONS: allocations
  end
end

On the master branch:

$ ruby --disable-gems -I lib -rmqtt/packet test.rb
{:ALLOCATIONS=>11}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}

On this branch:

$ ruby --disable-gems -I lib -rmqtt/packet test.rb
{:ALLOCATIONS=>6}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}

`Packet.read_byte` reads a byte from the socket and returns it.  Before
this commit it would allocate a string and an array, after this commit
it makes 0 allocations.

Here is a benchmark:

```ruby
require "mqtt/packet"

def count_alloc
  x = GC.stat(:total_allocated_objects)
  yield
  GC.stat(:total_allocated_objects) - x
end

File.open(__FILE__) do |f|
  10.times do
    allocations = count_alloc do
      MQTT::Packet.read_byte f
    end

    p ALLOCATIONS: allocations
  end
end
```

On the master branch:

```
$ ruby --disable-gems -I lib -rmqtt/packet test.rb
{:ALLOCATIONS=>11}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
{:ALLOCATIONS=>3}
```

On this branch:

```
$ ruby --disable-gems -I lib -rmqtt/packet test.rb
{:ALLOCATIONS=>6}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
{:ALLOCATIONS=>0}
```
@njh njh merged commit 49a73b8 into njh:master Mar 8, 2021
@njh
Copy link
Owner

njh commented Mar 8, 2021

Thanks Aaron!

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.

2 participants