Avoid creating unnecessary objects, especially in frequently executed code paths. This includes being mindful of implicit object allocations from common Ruby operations like array methods, string concatenations, and temporary variable creation.
Avoid creating unnecessary objects, especially in frequently executed code paths. This includes being mindful of implicit object allocations from common Ruby operations like array methods, string concatenations, and temporary variable creation.
Key practices:
first(n)
, flatten
, or map
<<
) over concatenation (+) for stringsExample - Before:
def process_items
first_two = items.first(2) # Creates new array
result = first_two.map { |x| x.to_s } # Creates another array
result.flatten.compact # Creates more arrays
end
Example - After:
def process_items
result = []
items.each_with_index do |item, index|
break if index >= 2
result << item.to_s # Single array, built incrementally
end
result
end
This optimization is especially important in hot code paths, such as request processing or data transformation pipelines, where the cumulative effect of unnecessary allocations can impact performance and trigger more frequent garbage collection.
Enter the URL of a public GitHub repository