我原本以为new String[list.size()]
是最快的,但是这似乎会导致Vector的额外锁定,使其变慢。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
public class Main {
private static final String[] NO_STRINGS = {};
private static final int runs = 50000000;
public static void main(String... args) {
List<String> strings = Arrays.asList("one,two,three,four,five,six".split(","));
List<String> arrayList = new ArrayList<String>(strings);
Vector<String> vector = new Vector<String>(strings);
testNoStrings(arrayList);
testStrings0(arrayList);
testSize(arrayList);
testNoStrings(vector);
testStrings0(vector);
testSize(vector);
}
private static String[] testSize(List<String> list) {
String[] ret = null;
long start = System.nanoTime();
for (int i = 0; i < runs; i++)
ret = list.toArray(new String[list.size()]);
long time = System.nanoTime() - start;
System.out.printf(list.getClass().getSimpleName() + " Using new String[list.size()] took an average of %,d ns%n", time/runs);
return ret;
}
private static String[] testNoStrings(List<String> list) {
String[] ret = null;
long start = System.nanoTime();
for (int i = 0; i < runs; i++)
ret = list.toArray(NO_STRINGS);
long time = System.nanoTime() - start;
System.out.printf(list.getClass().getSimpleName() + " Using NO_STRINGS took an average of %,d ns%n", time/runs);
return ret;
}
private static String[] testStrings0(List<String> list) {
String[] ret = null;
long start = System.nanoTime();
for (int i = 0; i < runs; i++)
ret = list.toArray(new String[0]);
long time = System.nanoTime() - start;
System.out.printf(list.getClass().getSimpleName() + " Using new String[0] took an average of %,d ns%n", time/runs);
return ret;
}
}
你看到任何差别极有可能是机器依赖,但一个明显的因素是,ArrayList的比向量更快。
ArrayList Using NO_STRINGS took an average of 17 ns
ArrayList Using new String[0] took an average of 22 ns
ArrayList Using new String[list.size()] took an average of 27 ns
Vector Using NO_STRINGS took an average of 28 ns
Vector Using new String[0] took an average of 29 ns
Vector Using new String[list.size()] took an average of 46 ns
每一百万的时间和发现。 –
你为什么不以他们为基准并亲眼看到? – NPE
当您应该使用ArrayList时使用Vector可能会产生更大的差异。 –