2011-09-21 84 views
-2

可能更好的性能复制在矢量字符串数组

至于有人问How to convert Vector to String array in java

哪一个是店面最佳性能的矢量值到字符串数组。以及它如何在后台执行?

Vector<String> v = new Vector<String>(); 
// this one 
String s[] = v.toArray(new String[v.size()]); 
// or this one 
String s[] = v.toArray(new String[0]); 
+0

每一百万的时间和发现。 –

+0

你为什么不以他们为基准并亲眼看到? – NPE

+2

当您应该使用ArrayList时使用Vector可能会产生更大的差异。 –

回答

2

根据经验,一般情况下,它的速度更快适当大小的数组或集合的第一次,因为它可以避免在一次或多次后调整其大小。减少工作==更快。顺便说一句,你几乎肯定不应该使用Vector;在绝大多数情况下,ArrayList是更好的选择。

更新:对于您的特定情况,结果将严重依赖于您的Vector中的数据。与任何关于性能的问题一样,您应该自己对其进行简介。既然你说你不知道如何进行基准测试,我建议你阅读关于Java应用程序的分析和性能测量。如果你不测量东西,你不应该浪费时间担心标准库操作的性能。您可能担心的是与您的应用程序中的实际瓶颈无关的事情。

2

我原本以为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