简体   繁体   中英

Iteration vs order_by() efficiency

I'm trying to find the highest cost item from a queryset, and I'm just wondering which of the following (if either) is more efficient

items = Item.objects.all()

highest_cost = max(item.cost for item in items)
#Or
highest_cost = items.order_by('-cost')[0].cost

I'm not super concerned about performance, I'm mostly just curious.

First of all, you can simply use django's Max aggregation .

items = Item.objects.all()
items.aggregate(Max('cost'))

Secondly, the answer to your question depends on various factors. Eg if the table is very big (many records, or particularly big records), you would need to avoid retrieving all of them while only needing one (first query). However, if you have millions of records in the table, and no index on the column you order by, sorting can be very slow (O(nlogn)), while finding the max is O(n).

In most cases, however, letting the DB server do the job (in your example, using order by ) should be faster.

order_by要快得多,特别是如果数据库中有很多条目。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM