list.toArray has better performance with size! I remembered.
If you google a little, all the pages are written like that based on the internal implementation.
However, VM performance is also evolving day by day.
As of May 31, 2018, is that really the case?
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
list.add(Integer.toString(i));
}
int[] loopCounts = new int[] { 1000, 10000, 100000, 1000000, 10000000 };
for (int loop : loopCounts) {
long sum = 0;
for (int j = 0; j < 10; j++) {
long start = System.currentTimeMillis();
String[] temp = null;
for (int i = 0; i < loop; i++) {
temp = list.toArray(new String[0]);
}
long stop = System.currentTimeMillis();
sum += stop - start;
}
System.out.println("toArray(new String[0]) " + loop + "Speed of times*The average speed of 10 times is" + sum / 10 + "It's a millisecond.");
sum = 0;
for (int j = 0; j < 10; j++) {
long start = System.currentTimeMillis();
String[] temp = null;
for (int i = 0; i < loop; i++) {
temp = list.toArray(new String[list.size()]);
}
long stop = System.currentTimeMillis();
sum += stop - start;
}
System.out.println("toArray(new String[list.size()]) " + loop + "Speed of times*The average speed of 10 times is" + sum / 10 + "It's a millisecond.");
}
}
}
toArray (new String [0]) 1000 times speed * 10 times The average speed is 2 milliseconds.
toArray (new String [list.size ()]) 1000 times speed * 10 times The average speed is 2 milliseconds.
toArray (new String [0]) 10000 times speed * 10 times The average speed is 19 milliseconds.
toArray (new String [list.size ()]) 10000 times speed * 10 times The average speed is 25 milliseconds.
toArray (new String [0]) 100000 times speed * 10 times The average speed is 207 milliseconds.
toArray (new String [list.size ()]) 100000 times speed * 10 times The average speed is 288 milliseconds.
toArray (new String [0]) 1000000 times speed * 10 times The average speed is 1497 milliseconds.
toArray (new String [list.size ()]) 1000000 times speed * 10 times The average speed is 1562 milliseconds.
toArray (new String [0]) 10000000 times speed * 10 times The average speed is 12949 milliseconds.
toArray (new String [list.size ()]) 10000000 times speed * 10 times The average speed is 15622 milliseconds.
** toArray (new T [0]) is faster! ** **
It's crazy because it's written in an article that came out on the net (self-discipline)
External link: Arrays of Wisdom of the Ancients
Recommended Posts