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

Performance improvements, calculate attributes to serialize only once #98

Merged
merged 4 commits into from
Oct 6, 2022

Conversation

Bhacaz
Copy link
Collaborator

@Bhacaz Bhacaz commented Oct 6, 2022

1.1704x faster

Benchmark
require_relative './lib/bright_serializer'

class User
  attr_accessor :friends, :id, :first_name, :last_name
  def initialize(id, first_name, last_name)
    @id = id
    @first_name = first_name
    @last_name = last_name
  end
end

class UserSerializer
  include BrightSerializer::Serializer
  attributes :id, :first_name, :last_name

  attribute :friends do |object|
    UserSerializer.new(object.friends, fields: [:id, :first_name])
  end
end


list = 100.times.map { |i| User.new(i, "first_name_#{i}", "last_name_#{i}") }
list.each do |user|
  user.friends = list.sample(10).map { |u| nu = u.dup; nu.friends = nil; nu }
end

require 'benchmark/ips'

Benchmark.ips do |x|
  x.report('A') do
    UserSerializer.new(list).to_hash
  end
  x.compare!
end

# A      1.104k (± 1.4%) i/s -      5.618k in   5.089321s
# A    959.739  (± 1.6%) i/s -      4.800k in   5.002612s
# 1.1704x faster

Fix and add specs for coverage

@Bhacaz Bhacaz merged commit 95e7b9c into master Oct 6, 2022
@Bhacaz Bhacaz deleted the calculate_attribute_once branch October 6, 2022 01:10
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.

None yet

1 participant