Skip to content

Commit

Permalink
Cache JSON generation for individual messages
Browse files Browse the repository at this point in the history
  • Loading branch information
rohitpaulk committed Jan 6, 2018
1 parent e14207d commit 874c417
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 7 deletions.
11 changes: 5 additions & 6 deletions lib/segment/analytics/message.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
require 'forwardable'

require 'segment/analytics/defaults'

module Segment
class Analytics
# Represents a message to be sent to the API
class Message
extend Forwardable

def initialize(hash)
@hash = hash
end
Expand All @@ -16,8 +12,11 @@ def too_big?
to_json.bytesize > Defaults::Message::MAX_BYTES
end

def_delegators :@hash, :to_json # TODO: Cache and reuse
def_delegators :@hash, :[]
# Since the hash is expected to not be modified (set at initialization),
# the JSON version can be cached after the first computation.
def to_json(*args)
@json ||= @hash.to_json(*args)
end
end
end
end
2 changes: 1 addition & 1 deletion lib/segment/analytics/message_batch.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def <<(message)
end
end

def_delegators :@messages, :to_json # TODO: Cache and reuse
def_delegators :@messages, :to_json
def_delegators :@messages, :clear
def_delegators :@messages, :empty?
def_delegators :@messages, :length
Expand Down
35 changes: 35 additions & 0 deletions spec/segment/analytics/message_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
require 'spec_helper'

module Segment
class Analytics
describe Message do
describe '#to_json' do
it 'caches JSON conversions' do
# Keeps track of the number of times to_json was called
nested_obj = Class.new do
attr_reader :to_json_call_count

def initialize
@to_json_call_count = 0
end

def to_json(*_)
@to_json_call_count += 1
'{}'
end
end.new

message = Message.new('some_key' => nested_obj)
expect(nested_obj.to_json_call_count).to eq(0)

message.to_json
expect(nested_obj.to_json_call_count).to eq(1)

# When called a second time, the call count shouldn't increase
message.to_json
expect(nested_obj.to_json_call_count).to eq(1)
end
end
end
end
end

0 comments on commit 874c417

Please # to comment.