Home  >  Article  >  Java  >  `toArray(new MyClass[0]) vs. toArray(new MyClass[myList.size()]): Which is More Performant?`

`toArray(new MyClass[0]) vs. toArray(new MyClass[myList.size()]): Which is More Performant?`

DDD
DDDOriginal
2024-11-24 17:28:13425browse

`toArray(new MyClass[0]) vs. toArray(new MyClass[myList.size()]): Which is More Performant?`

toArray(new MyClass[0]) or toArray(new MyClass[myList.size()]) Performance Implications

When converting an ArrayList to an array, developers can choose between two approaches:

  • MyClass[] arr = myList.toArray(new MyClass[myList.size()]);
  • MyClass[] arr = myList.toArray(new MyClass[0]);

While the second option is less verbose, it raises questions about possible performance considerations.

Benchmark Analysis

To determine the performance impact, benchmarks were conducted using JMH on Hotspot 8. The results revealed that using an empty array consistently outperforms presizing the array:

Benchmark                      (n)  Mode  Samples    Score   Error  Units
c.a.p.SO29378922.preSize         1  avgt       30    0.025 ▒ 0.001  us/op
c.a.p.SO29378922.preSize       100  avgt       30    0.155 ▒ 0.004  us/op
...
c.a.p.SO29378922.resize        100  avgt       30    0.133 ▒ 0.003  us/op
c.a.p.SO29378922.resize       1000  avgt       30    1.075 ▒ 0.022  us/op
...

Explanation

This counterintuitive finding can be attributed to optimizations employed by the JVM and JIT compiler. These optimizations allow for the creation and initialization of correctly sized arrays efficiently without the need for user-supplied dimensions.

Recommendation

Based on benchmark results and analysis, it is recommended to use:

MyClass[] arr = myList.toArray(new MyClass[0]);

This not only improves performance but also aligns with the principle of letting the JVM optimize common operations such as array creation.

The above is the detailed content of `toArray(new MyClass[0]) vs. toArray(new MyClass[myList.size()]): Which is More Performant?`. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn