Prompt
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:
- Avoid unnecessary array allocations from methods like
first(n),flatten, ormap - Use direct iteration instead of intermediate collections when possible
- Consider using mutation methods (e.g.,
<<) over concatenation (+) for strings - Cache computed values that are reused frequently
Example - 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.