C ++和Java性能 [英] C++ and Java performance

查看:105
本文介绍了C ++和Java性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题只是推测。

我在C ++中有以下实现:

I have the following implementation in C++:

using namespace std;

void testvector(int x)
{
  vector<string> v;
  char aux[20];
  int a = x * 2000;
  int z = a + 2000;
  string s("X-");
  for (int i = a; i < z; i++)
  {
    sprintf(aux, "%d", i);
    v.push_back(s + aux);
  }
}

int main()
{
  for (int i = 0; i < 10000; i++)
  {
    if (i % 1000 == 0) cout << i << endl;
    testvector(i);
  }
}



在我的盒子里, 12秒;令人惊讶的是,我在Java中使用类似的实现[使用String和ArrayList],它的运行速度比我的C ++应用程序(约2秒)快。

In my box, this program gets executed in approx. 12 seconds; amazingly, I have a similar implementation in Java [using String and ArrayList] and it runs lot faster than my C++ application (approx. 2 seconds).

HotSpot在翻译为native时会执行大量的优化,但是我认为如果这样的性能可以在Java中完成,它可以在C ++中实现...

I know the Java HotSpot performs a lot of optimizations when translating to native, but I think if such performance can be done in Java, it could be implemented in C++ too...

你认为应该在上面的程序中修改什么,或者,我dunno,在使用的库或内存分配器中达到类似的性能在这个东西? (写这些东西的实际代码可能很长,所以,讨论这将是巨大的)...

So, what do you think that should be modified in the program above or, I dunno, in the libraries used or in the memory allocator to reach similar performances in this stuff? (writing actual code of these things can be very long, so, discussing about it would be great)...

谢谢。

推荐答案

你必须小心性能测试,因为很容易欺骗自己或不像比较喜欢。

You have to be careful with performance tests because it's very easy to deceive yourself or not compare like with like.

然而,我已经看到类似的结果比较C#和C + +,并有一些知名的博客文章关于本机编码器的惊讶当面对这种证据。基本上,一个好的现代代数压缩GC对于大量小分配是非常优化的。

However, I've seen similar results comparing C# with C++, and there are a number of well-known blog posts about the astonishment of native coders when confronted with this kind of evidence. Basically a good modern generational compacting GC is very much more optimised for lots of small allocations.

在C ++的默认分配器中,每个块都被视为相同,分配和释放。在代GC中,所有块的分配非常非常便宜(几乎和堆栈分配一样便宜),如果它们是短暂的,那么它们也很便宜清理。

In C++'s default allocator, every block is treated the same, and so are averagely expensive to allocate and free. In a generational GC, all blocks are very, very cheap to allocate (nearly as cheap as stack allocation) and if they turn out to be short-lived then they are also very cheap to clean up.

这就是为什么C ++与更现代的语言相比的快速性能 - 大部分是神话。你必须手动调整你的C ++程序的所有识别,然后才能与一个等效的天真的书面C#或Java程序的性能竞争。

This is why the "fast performance" of C++ compared with more modern languages is - for the most part - mythical. You have to hand tune your C++ program out of all recognition before it can compete with the performance of an equivalent naively written C# or Java program.

这篇关于C ++和Java性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆