PERF: optimize performance of message generation

PERF: optimize performance of message generation

# frozen_string_literal: true

require_relative '../rerunner/rerunner'
require 'benchmark/ips'

def append(global_id,message_id,channel,data)
  global_id.to_s << "|" << message_id.to_s << "|" << channel.gsub("|", "$$123$$") << "|" << data
end

def interpolate(global_id,message_id,channel,data)
  "#{global_id}|#{message_id}|#{channel.gsub("|", "$$123$$")}|#{data}"
end

if interpolate(1,2,"a|b","data") != append(1,2,"a|b","data")
  raise "bad implementation"
end


Benchmark.ips do |x|
  x.warmup = 1
  x.time = 10

  x.report("<<") do |times|
    while times > 0
      append(1,2,"three","four")
      times -= 1
    end
  end

  x.report("interpolate") do |times|
    while times > 0
      interpolate(1,2,"three","four")
      times -= 1
    end
  end

  x.compare!
end
Calculating -------------------------------------
                  <<      2.254M (± 1.0%) i/s -     22.619M in  10.036563s
         interpolate      2.398M (± 0.9%) i/s -     24.143M in  10.067638s

Comparison:
         interpolate:  2398259.8 i/s
                  <<:  2253830.6 i/s - 1.06x  slower

Also fixed #227

diff --git a/lib/message_bus/message.rb b/lib/message_bus/message.rb
index 51b16fb..ee988bf 100644
--- a/lib/message_bus/message.rb
+++ b/lib/message_bus/message.rb
@@ -20,10 +20,10 @@ class MessageBus::Message < Struct.new(:global_id, :message_id, :channel, :data)
 
   # only tricky thing to encode is pipes in a channel name ... do a straight replace
   def encode
-    global_id.to_s << "|" << message_id.to_s << "|" << channel.gsub("|", "$$123$$") << "|" << data
+    "#{global_id}|#{message_id}|#{channel.gsub("|", "$$123$$")}|#{data}"
   end
 
   def encode_without_ids
-    channel.gsub("|", "$$123$$") << "|" << data
+    "#{channel.gsub("|", "$$123$$")}|#{data}"
   end
 end

GitHub sha: 81bb5949

1 Like