Skip to content

Mass Assignment is slow #134

@dnagir

Description

@dnagir

The mass assignment is almost 3x slower than the "semi-manual" assignment using send.

This becomes a bigger issue as more attributes are added.
We have a model with ~30 attributes which is used very often and becomes a real bottleneck in the app.

The only workaround is not to use the mass-assignment.

Some benchmarks:

                       user     system      total        real
mass assignement   0.890000   0.000000   0.890000 (  0.888365)
assign manually    0.350000   0.000000   0.350000 (  0.350524)

the BM code:

require 'active_attr'
require 'benchmark'

class Info
  include ActiveAttr::Model

  10.times do |n|
    attribute "str#{n}", type: String
  end

  10.times do |n|
    attribute "int#{n}", type: Integer
  end

  10.times do |n|
    attribute "attr#{n}"
  end
end



hash_values = {}
10.times do |n|
  hash_values["str#{n}"] = "string #{n}"
  hash_values["int#{n}"] = n
  hash_values["attr#{n}"] = "another value #{n}"
end



def mass_assign(values)
  Info.new(values)
end

def assign_manually(values)
  i = Info.new
  values.each do |k, v|
    i.send("#{k}=", v)
  end
end


iterations = 5000
Benchmark.bm(16) do |bm|
  bm.report('mass assignement') { iterations.times { mass_assign(hash_values) } }
  bm.report('assign manually')  { iterations.times { assign_manually(hash_values) } }
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions