ActiveRecords select(:id).collect vs. pluck(:id) methods: Why is pure AR “pluck” slower?

喜欢而已 提交于 2019-12-01 04:42:43

Your benchmark is inaccurate. First of all, as you can see, both executions on the database side triggers the same query

SELECT "articles"."id" FROM "articles"

Therefore, the database time should be considered irrelevant. Clearly the two queries had different execution time as shown by the console, but this is normal as if you run the same query 100 times the execution time can be different each time as it depends by a variety of variables such as the machine load, the database state, etc.

Since the database execution time can be considered equivalent, it's irrelevant for the benchmark.

Therefore, what you need to compare is the Ruby execution time and allocation. Pluck is supposed to be faster and more lightweight as compared to collect it doesn't allocate ActiveRecord objects, rather it returns only the selected values.

If you really want to benchmark the methods, you should mock the database time (which is clearly variable but irrelevant for this benchmark) and only benchmark allocation and the two different Ruby methods.

Long story short, pluck is generally more efficient.

Pravesh Khatri

select is used to fetch records with specific attributes. It returns an ActiveRecord::Relation object.

pluck can be used the same way select is used, however it returns an array of selected attributes.

You can go through this article.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!