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
Replacing plus with push in array #38808
Replacing plus with push in array #38808
Conversation
We're now mutating the return value from (Note for future reports: creating a new object_id isn't troublesome and what we'd fix, it's that it signifies a new array gets created and therefore allocates more memory) |
Hi @kaspth , I have kept the first line as it is. I have done benchmarking of the memory allocation and I found out there is a significant difference in memory allocation as you can see from the below: (irb) 32 Object benchmarking_method_old 104 Array (irb) 21 Object benchmarking_method 208 Array |
Yes, there’s fewer Array allocations, that doesn’t mean I want to set a precedent where we start microoptimizing without knowing the context. Please address my other questions 😊 I don’t like that we’ve just swapped the super line back to + just like that, feels like we don’t know what we’re doing here. |
I think it doesn’t matter much as the upper bound is fixed but I think sometime later we should micro optimise each file for providing best performance. What’s your suggestion @kaspth ? |
Absolutely not. We generally optimize for readability because that’s way more important most of the time to such a large codebase. If what we “optimize” has 0.000001 impact on an actual app, it’s been a waste of everybody’s time. Sorry, I don’t think it’s worth continuing this. There’s too much need for conversation for a relatively questionable gain. Appreciate the attempt 🙏 |
Summary
Every time an object is getting added using "+" and is being assigned to itself. The new object id is created. Instead, we should use a "push" in which a new object id is not created.
Sample code to explain this:
:001 > valid = [:counter_cache, :join_table, :index_errors]
=> [:counter_cache, :join_table, :index_errors]
002 > valid.object_id
=> 70353367984560
003 > valid += [:as, :foreign_type]
=> [:counter_cache, :join_table, :index_errors, :as, :foreign_type]
004 > valid.object_id
=> 70353359749500
005 > valid.push(:through, :source, :source_type)
=> [:counter_cache, :join_table, :index_errors, :as, :foreign_type, :through, :source, :source_type]
006 > valid.object_id
=> 70353359749500
Other Information