Skip to content
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

map().sum could be sum(xx) #187

Open
lelelelemon opened this issue Aug 23, 2017 · 1 comment
Open

map().sum could be sum(xx) #187

lelelelemon opened this issue Aug 23, 2017 · 1 comment

Comments

@lelelelemon
Copy link
Collaborator

ror_ecommerce/app/./models/cart.rb:107:    shopping_cart_items.map(&:total).sum
ror_ecommerce/app/./models/cart.rb:115:    shopping_cart_items.map(&:quantity).sum

to

shopping_cart_items.sum(:total)
shopping_cart_items.sum(:total)

doing sum is faster in db side

@drhenner
Copy link
Owner

hmmm. I guess my answer is "it depends". If shopping_cart_items are loaded it's best to just do the math in ruby.

   shopping_cart_items.loaded? ? shopping_cart_items.map(&:total).sum : shopping_cart_items.sum(:total)

Also I assume most times this method is used, shopping_cart_items will eventually be loaded. So maybe ruby math would be better. Plus if you need to run shopping_cart_items.sum(:total) & shopping_cart_items.sum(:quantity) you now have two queries then a possible 3rd query later if shopping_cart_item objects are needed.

I think optimizing this will eventually be up to the implementation. The frontend of ror_ecommerce will be updated by most sites and hence I'm leaning toward keeping the method as it currently stands and let any dev optimize for their site.

That said, this is interesting and I'd like to here your thoughts on my reasoning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants