Array/Vector作为方法参数

Paw*_*ela 1 java performance vector

我一直认为我们应该在Java中使用Vector,并且没有性能问题,这当然是正确的.我正在编写一种计算MSE(均方误差)的方法,并注意到它非常慢 - 我基本上是传递了值的向量.当我切换到Array时,速度提高了10倍,但我不明白为什么.

我写了一个简单的测试:

public static void main(String[] args) throws IOException {

    Vector <Integer> testV = new Vector<Integer>();
    Integer[] testA = new Integer[1000000];
    for(int i=0;i<1000000;i++){
        testV.add(i);
        testA[i]=i;
    }

    Long startTime = System.currentTimeMillis();
    for(int i=0;i<500;i++){
        double testVal = testArray(testA, 0, 1000000);
    }
    System.out.println(String.format("Array total time %s ",System.currentTimeMillis() - startTime));

    startTime = System.currentTimeMillis();
    for(int i=0;i<500;i++){
        double testVal = testVector(testV, 0, 1000000);
    }
    System.out.println(String.format("Vector total time %s ",System.currentTimeMillis() - startTime));

}
Run Code Online (Sandbox Code Playgroud)

其中调用以下方法:

public static double testVector(Vector<Integer> data, int start, int stop){
    double toto = 0.0;
    for(int i=start ; i<stop ; i++){
        toto += data.get(i);
    }

    return toto / data.size();
}

public static double testArray(Integer[] data, int start, int stop){
    double toto = 0.0;
    for(int i=start ; i<stop ; i++){
        toto += data[i];
    }

    return toto / data.length;
}
Run Code Online (Sandbox Code Playgroud)

阵列1确实快了10倍.这是输出:

数组总时间854矢量总时间9840

有人可以解释一下为什么吗?我已经搜索了很长一段时间,但无法弄明白.向量方法似乎是制作向量的本地副本,但我一直认为在Java中通过引用传递的对象.

The*_*ind 13

我一直认为我们应该在Java中使用Vector,并且没有性能问题 - 错了.向量是线程安全的,因此它需要额外的逻辑(代码)来处理多个线程的访问/修改因此,它很慢.另一方面,数组不需要额外的逻辑来处理多个线程.你应该尝试ArrayList而不是Vector提高速度

注意(根据您的评论):我每次运行500次方法

这不是衡量java 性能/速度的正确方法.你应该ATLEAST给予热身赛来看,以抵消的作用JIT.