Re: Why is java consumer/producer so much faster than C++
In comp.lang.c++ Melzzzzz <mel@zzzzz.com> wrote:
I even tried c++ without dynamic
memory management (except queue itself) and that is *even slower*.
If two C++ programs are otherwise identical, except that one uses
'new int' and the other just uses the ints by value, and the former
is faster than the latter, then there's something horribly wrong in
the way you are measuring, or something else. I don't think it's
physically possible for 'new int' to be faster than using ints by
value under any possible circumstance, even if we assumed a highly
optimized version of 'new' that does magic under the hood to be 10
times faster than the regular 'new'.
std::unique_lock<std::mutex> lock(m_);
produced.put(std::unique_ptr<int>(new int(i)));
arr[std::rand()%size] = produced.take();
I don't know what's the cause of the slowness in your program, but
I quoted above the three possible culprits I would first investigate
(which happen to be in order of likeliness).
Locks are slow. They are probably slower than 'new'.
'new' is slow, especially when compared to java's.
std::rand() is slow, although probably does not account for that much
slowness, but could be a minor contributing factor.