Hibernate中的orderBy与Collections.sort()的区别。

huangapple go评论63阅读模式
英文:

Difference between orderBy of hibernate and Collections.sort()

问题

使用Hibernate的orderBy和Java的Collections.sort()有什么区别?Collections.sort()的时间复杂度为O(nlogn),而使用orderBy必须是O(1)。然而,数据库处理肯定也会有一些开销。在无法使用orderBy的情况下,使用Collections.sort()是否可以接受?

英文:

What is the difference between using order by of hibernate and Collections.sort() of Java? The time complexity of Collections.sort() is O(nlogn) and using orderBy must be O(1). However, the db processing must have some overhead too. Is it okay to use Collections.sort() in cases where using orderBy is not possible?

答案1

得分: 1

请注意,数据库上的 order by 适用于所有行。而您只能将 Collections.sort 应用于“已加载”的行。

因此,如果您有 1000 行数据,并且想要根据某个顺序选择前 10 行,如果使用 Collections.sort,您需要在排序之前获取所有行,而使用 order by,您只需选择所需的 10 行。

英文:

Keep in mind that an order by on the db applies on all the rows. While you can only apply Collections.sort to "loaded" rows.

So, if you have 1000 rows, and you want to select the first 10 according to an order, to use Collections.sort you would need to get all rows before sorting, while with order by you would only select the 10 you want.

答案2

得分: 1

你可以任选其一。通常情况下,它们都应该是O(nlogn)(因为数据库还必须应用排序算法,而这并不比Collections中的排序算法更优)。

如果可能的话,我会使用数据库的orderBy方法(*),因为这样你可以限制从数据库中发送的数据量(至少在你仅关心匹配数据的前部分的情况下)。

(*) 有些情况下,你可能希望实现一种“奇怪”的排序顺序(比如“按第三个单词的第二个字母排序”),这种情况下最好在Java中实现,但在大多数情况下,orderBy已经足够,因此更可取。

英文:

You can use either one. Generally they should both be O(nlogn) (since the database also has to apply a sorting algorithm and it is not better than the sorting algorithm in Collections).

I would use the database's orderBy if possible (*), since you then can limit the amount of data that are sent from the database (at least in cases where you'r only interested in the first part of the matching data).

(*) There are situations where you want you want to implement a "weird" sort order (ie "sort by the 2nd letter of the third word"), and then it is better to do it in Java, but in most cases orderBy is sufficient and hence preferrable.

huangapple
  • 本文由 发表于 2020年3月15日 22:27:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/60693928.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定