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

Optimize initializer #56

Merged
merged 2 commits into from
Mar 22, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 19 additions & 8 deletions lib/values.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,28 @@ def self.new(*fields, &block)
Class.new do
attr_reader(:hash, *fields)

define_method(:initialize) do |*values|
raise ArgumentError.new("wrong number of arguments, #{values.size} for #{fields.size}") if fields.size != values.size
# Unroll the fields into a series of assignment Ruby statements that can
# be used inside of the initializer for the new class. This was introduced
# in PR#56 as a performance optimization -- it ensures that this iteration
# happens once per class, instead of happening once per instance of the
# class.
instance_var_assignments = Array.new(fields.length) do |idx|
"@#{fields[idx]} = values[#{idx}]"
end.join("\n")

class_eval <<-RUBY
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this looks great, thanks! Mind adding a comment here mentioning this optimization? Whilst this library doesn't change much, I like to prevent opportunities for bitrot where possible.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review -- I added a comment above this section to explain a bit more of what's happening and to point back to the PR. Does that cover what you were hoping for?

def initialize(*values)
if #{fields.size} != values.size
raise ArgumentError.new("wrong number of arguments, \#{values.size} for #{fields.size}")
end

fields.zip(values) do |field, value|
instance_variable_set(:"@#{field}", value)
end
#{instance_var_assignments}

@hash = self.class.hash ^ values.hash
@hash = self.class.hash ^ values.hash

freeze
end
freeze
end
RUBY

const_set :VALUE_ATTRS, fields

Expand Down