Java重写hashCode()方法有任何性能问题吗? [英] Java Overriding hashCode() method has any Performance issue?

查看:152
本文介绍了Java重写hashCode()方法有任何性能问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将覆盖 hashCode()方法,它会降低应用程序的性能。我在我的应用程序的许多地方重写了这个方法。

If i will override hashCode() method will it degrade the performance of application. I am overriding this method in many places in my application.

推荐答案

是的,如果hashCode你可以降低散列集合的性能方法以不好的方式实现。 hashCode方法的最佳实现应该为唯一对象生成唯一的hashCode。唯一的hashCode将避免冲突,并且可以使用 O(1)复杂度存储和检索元素。但是只有hashCode方法才能做到这一点,你需要重写equals方法来帮助JVM。

Yes you can degrade the performance of a hashed collection if the hashCode method is implemented in a bad way. The best implementation of a hashCode method should generate the unique hashCode for unique objects. Unique hashCode will avoid collisions and an element can be stored and retrieved with O(1) complexity. But only hashCode method will not be able to do it, you need to override the equals method also to help the JVM.

如果hashCode方法无法生成唯一的对于唯一对象的哈希,那么您有可能在桶中持有多个对象。当您有两个具有相同哈希的元素但equals方法为它们返回false时,会发生这种情况。所以每次发生这种情况时,元素都会被添加到散列桶中的列表中。这将减慢元素的插入和后退。这将导致get方法的 O(n)复杂性,其中n是存储桶中列表的大小。

If the hashCode method is not able to generate unique hash for unique objects then there is a chance that you will be holding more than one objects at a bucket. This will occur when you have two elements with same hash but equals method returns false for them. So each time this happens the element will be added to the list at hash bucket. This will slow down both the insertion and retreival of elements. It will lead to O(n) complexity for the get method, where n is the size of the list at a bucket.

注意:当您尝试为hashCode实现中的唯一对象生成唯一哈希时,请确保为此执行编写简单算法。如果用于生成散列的算法太重,那么您在散列集合上的操作肯定会表现不佳。因为哈希集合上的大多数操作都会调用hashCode方法。

Note: While you try to generate unique hash for unique objects in your hashCode implementation, be sure that you write simple algorithm for doing so. If your algorithm for generating the hash is too heavy then you will surely see a poor performance for operations on your hashed collection. As hashCode method is called for most of the operations on the hashed collection.

这篇关于Java重写hashCode()方法有任何性能问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆