Optimized version of CopiesList.hashCode()
Martin Buchholz
martinrb at google.com
Tue Nov 27 03:17:41 UTC 2018
I agree!
(but don't have time ...)
On Sun, Nov 25, 2018 at 9:01 PM, Zheka Kozlov <orionllmain at gmail.com> wrote:
> Currently, CopiesList.hashCode() is inherited from AbstractList which:
>
> - calls hashCode() for each element,
> - creates a new Iterator every time.
>
> However, for Collections.nCopies():
>
> - All elements are the same. So hashCode() can be called only once.
> - An Iterator is unnecessary.
>
> So, I propose overridding hashCode() implementation for CopiesList:
>
> @Override
> public int hashCode() {
> int hashCode = 1;
> final int elementHashCode = (element == null) ? 0 : element.hashCode();
> for (int i = 0; i < n; i++) {
> hashCode = 31*hashCode + elementHashCode;
> }
> return hashCode;
> }
>
> Benchmark:
> List<List<String>> list = Collections.nCopies(10_000, new
> ArrayList<>(Collections.nCopies(1_000_000, "a")));
> long nano = System.nanoTime();
> System.out.println(list.hashCode());
> System.out.println((System.nanoTime() - nano) / 1_000_000);
>
> Result:
> Old version - ~12 seconds.
> New version - ~10 milliseconds.
>
More information about the core-libs-dev
mailing list