首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么Java读取大文件的速度比C++快?

为什么Java读取大文件的速度比C++快?
EN

Stack Overflow用户
提问于 2014-04-09 15:04:17
回答 3查看 8.6K关注 0票数 54

我有一个2 GB的文件(iputfile.txt),其中文件中的每一行都是一个单词,就像这样:

apple
red
beautiful
smell
spark
input

我需要写一个程序来读取文件中的每个单词并打印单词计数。我用Java和C++写的,但结果令人惊讶: Java比C++快2.3倍。我的代码如下:

C++:

int main() {
    struct timespec ts, te;
    double cost;
    clock_gettime(CLOCK_REALTIME, &ts);

    ifstream fin("inputfile.txt");
    string word;
    int count = 0;
    while(fin >> word) {
        count++;
    }
    cout << count << endl;

    clock_gettime(CLOCK_REALTIME, &te);
    cost = te.tv_sec - ts.tv_sec + (double)(te.tv_nsec-ts.tv_nsec)/NANO;
    printf("Run time: %-15.10f s\n", cost);

    return 0;
}

输出:

5e+08
Run time: 69.311 s

Java:

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

    long startTime = System.currentTimeMillis();

    FileReader reader = new FileReader("inputfile.txt");
    BufferedReader br = new BufferedReader(reader);
    String str = null;
    int count = 0;
    while((str = br.readLine()) != null) {
        count++;
    }
    System.out.println(count);

    long endTime = System.currentTimeMillis();
    System.out.println("Run time : " + (endTime - startTime)/1000 + "s");
}

输出:

5.0E8
Run time: 29 s

在这种情况下,为什么Java比C++快,如何提高C++的性能?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22955178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档