Skip to content

Commit

Permalink
Inline lambdas
Browse files Browse the repository at this point in the history
I couldn't find a reason for this pattern to call a method to get
a similar proc every time.

It does incur an extra method call, and a Proc object allocation.

In addition, in the case of `collection_converter`, the relatively
complex code can be replaced by a simpler and faster `map`.

Map is preferable over shifting objects into a new Array, because
it allows Ruby to directly allocate an Array of the right size
rather than to have to potentially resize it multiple times.

This isn't a big gain, but I think it makes the code easier to
read anyway.

Before:

```
Calculating -------------------------------------
                alba    801.321 (± 0.6%) i/s    (1.25 ms/i) -      4.080k in   5.091760s
Calculating -------------------------------------
                alba   826.321k memsize (     0.000  retained)
                         9.908k objects (     0.000  retained)
                         6.000  strings (     0.000  retained)
```

After:

```
Calculating -------------------------------------
                alba    830.039 (± 0.8%) i/s    (1.20 ms/i) -      4.182k in   5.038669s
Calculating -------------------------------------
                alba   818.241k memsize (     0.000  retained)
                         9.807k objects (     0.000  retained)
                         6.000  strings (     0.000  retained)
```
  • Loading branch information
byroot committed Mar 6, 2025
1 parent ad700cd commit afa1b13
Showing 1 changed file with 5 additions and 18 deletions.
23 changes: 5 additions & 18 deletions lib/alba/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def as_json(_options = {}, root_key: nil, meta: {})
#
# @return [Hash]
def serializable_hash
Alba.collection?(@object) ? serializable_hash_for_collection : converter.call(@object)
Alba.collection?(@object) ? serializable_hash_for_collection : attributes_to_hash(@object, {})
end
alias to_h serializable_hash

Expand Down Expand Up @@ -135,10 +135,12 @@ def serializable_hash_for_collection
@object.to_h do |item|
k = item.public_send(@_collection_key)
key = Alba.regularize_key(k)
[key, converter.call(item)]
[key, attributes_to_hash(item, {})]
end
else
@object.each_with_object([], &collection_converter)
@object.map do |obj|
attributes_to_hash(obj, {})
end
end
end

Expand Down Expand Up @@ -173,21 +175,6 @@ def transforming_root_key?
@_transforming_root_key
end

def converter
lambda do |obj|
attributes_to_hash(obj, {})
end
end

def collection_converter
lambda do |obj, a|
a << {}
h = a.last
attributes_to_hash(obj, h)
a
end
end

def attributes_to_hash(obj, hash)
attributes.each do |key, attribute|
set_key_and_attribute_body_from(obj, key, attribute, hash)
Expand Down

0 comments on commit afa1b13

Please sign in to comment.