Skip to content

Commit 781bc9e

Browse files
committed
Fixes #75: rule doc not up-to-date with changes in PMD
1 parent b729aab commit 781bc9e

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed
Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,34 @@
1-
A call to Collection.toArray can use the Collection's size vs an empty Array of the desired type.
1+
<!-- (c) 2019 PMD -->
2+
<p>
3+
Calls to a collection’s <code>toArray(E[])</code> method should specify a target array of zero size. This allows the
4+
JVM to
5+
optimize the memory allocation and copying as much as possible.
6+
</p>
7+
<p>
8+
Previous versions of this rule (pre PMD 6.0.0) suggested the opposite, but current JVM implementations
9+
perform always better, when they have full control over the target array. And allocation an array via
10+
reflection is nowadays as fast as the direct allocation.
11+
</p>
12+
<p>
13+
See also <a href="https://shipilev.net/blog/2016/arrays-wisdom-ancients/">Arrays of Wisdom of the Ancients</a>
14+
</p>
15+
<p>
16+
Note: If you don’t need an array of the correct type, then the simple <code>toArray()</code> method without an array
17+
is faster, but
18+
returns only an array of type <code>Object[]</code>.
19+
</p>
20+
<h2>Noncompliant Code Example</h2>
21+
<pre>
22+
List&lt;Foo&gt; foos = getFoos();
23+
24+
// inefficient, the array needs to be zeroed out by the jvm before it is handed over to the toArray method
25+
Foo[] fooArray = foos.toArray(new Foo[foos.size()]);
26+
</pre>
27+
<h2>Compliant Solution</h2>
28+
<pre>
29+
List&lt;Foo&gt; foos = getFoos();
30+
31+
// much better; this one allows the jvm to allocate an array of the correct size and effectively skip
32+
// the zeroing, since each array element will be overridden anyways
33+
Foo[] fooArray = foos.toArray(new Foo[0]);
34+
</pre>

0 commit comments

Comments
 (0)