Skip to content

Commit

Permalink
Optimize string transformation using String#tr
Browse files Browse the repository at this point in the history
This change was flagged by RuboCop and has been verified for
correctness and performance improvement. While Ruby 2.1 is no longer
tested in CI, `String#tr` is supported since that version, ensuring
backwards compatibility.

- Replace `gsub(/_/, '-')` with `tr('_', '-')` for better performance
- Improve `bench benchmark/data_attribute.haml` execution time by 20%
- Maintain compatibility with Ruby 2.1 (Haml's minimum required version)

Before:
```
### IPS
         haml v6.3.0     94.400k i/s (0.011ms) -    473.668k

### Memory
         haml v6.3.0     3.264k memsize (   600.000  retained)
                        41.000  objects (     9.000  retained)
                        19.000  strings (     6.000  retained)
```

After:
```
### IPS
         haml v6.3.0    113.201k i/s (0.009ms) -    568.672k

### Memory
         haml v6.3.0     2.808k memsize (   360.000  retained)
                        37.000  objects (     6.000  retained)
                        19.000  strings (     5.000  retained)
```

Refs:
- https://docs.ruby-lang.org/en/2.1.0/String.html#method-i-tr
- https://docs.rubocop.org/rubocop-performance/cops_performance.html#performancestringreplacement
  • Loading branch information
tagliala authored and amatsuda committed Aug 24, 2024
1 parent 8b1dab0 commit 3841f56
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion lib/haml/attribute_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def flatten_attributes(attributes)
if k.nil?
flattened[key] = v
else
flattened["#{key}-#{k.to_s.gsub(/_/, '-')}"] = v
flattened["#{key}-#{k.to_s.tr('_', '-')}"] = v
end
end
else
Expand Down

0 comments on commit 3841f56

Please sign in to comment.