gpt4 book ai didi

Java ArrayList 与 C++ std::vector

转载 作者:太空宇宙 更新时间:2023-11-04 12:42:45 28 4
gpt4 key购买 nike

<分区>

我只是想比较 Java 和 C++ 过滤列表的速度。只是为了好玩,因为我已经看到 C++ 有 std::vector.erase() 可以删除 vector 中的元素,所以我期望它比 Java 的等价物快很多,这是 Java 中的代码:

public static void main(String[] args) {

List<Integer> ints = new ArrayList<>(100000000);
long t1, t2;
int i;
t1 = System.currentTimeMillis();
for (i = 0; i < 100000000; i++) {
ints.add(i);
}
t2 = System.currentTimeMillis();

System.out.println("Initial array generated in " + (t2 - t1) + "ms");

t1 = System.currentTimeMillis();
List<Integer> result = ints.stream().filter((e) -> e % 2 == 0).collect(Collectors.toList());
t2 = System.currentTimeMillis();


System.out.println("Result: " + result.size() + " in " + (t2 - t1) + "ms.");
}

输出:

Initial array generated in 21859ms
Result: 50000000 in 3135ms.

这是 C++ 的等价物:

#include <iostream>
#include <vector>
#include <algorithm>
#include <sys/time.h>

long gettime(){

struct timeval time;
gettimeofday(&time, NULL);

long microsec = ((unsigned long long)time.tv_sec * 1000000) + time.tv_usec;

return microsec / 1000;

}
int main(int argc, char **argv){

std::vector<int> ints;

long t1 = gettime();
for(int i=0; i< 100000000; i++){
ints.push_back(i);
}
long t2 = gettime();

std::cout << "Initial array generated in " << (t2-t1) << "ms\n";


t1 = gettime();
ints.erase(std::remove_if(begin(ints), end(ints),
[](const int i){ return i%2==0;}), end(ints));

t2 = gettime();
std::cout << "Result: " << ints.size() << " in " << (t2-t1) << "ms.\n";

return 0;
}

C++ 输出:

Initial array generated in 1357ms
Result: 50000000 in 1323ms.

好的,所以数组过滤在 C++ 中快了 3 倍(老实说,我期待更多)。但问题是,为什么 Java 在填充列表时这么慢(22 秒)?

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com