Re: Do you use a garbage collector (java vs c++ difference in "new")
It's so unfair!
Razii $B<LF;!'(B
On Fri, 11 Apr 2008 03:35:27 +0300, Juha Nieminen
<nospam@thanks.invalid> wrote:
Razii wrote:
In C++, each "new" allocation request
will be sent to the operating system, which is slow.
That's blatantly false.
Well, my friend, I have proven you wrong. Razi has been victorious
once again :)
Time: 2125 ms (C++)
Time: 328 ms (java)
--- c++--
#include <ctime>
#include <cstdlib>
#include <iostream>
using namespace std;
class Test {
public:
Test (int c) {count = c;}
This is assignment after initialization.
It should be like this:
Test(int c) : count(c) {}
virtual ~Test() { }
int count;
};
int main(int argc, char *argv[]) {
clock_t start=clock();
for (int i=0; i<=10000000; i++) {
Test *test = new Test(i);
if (i % 5000000 == 0)
cout << test;
The memory you allocated is not released, so every new() is actually a
allocation operation to libc.
When the heap is empty, a new page of memory is allocated from OS.
}
clock_t endt=clock();
std::cout <<"Time: " <<
double(endt-start)/CLOCKS_PER_SEC * 1000 << " ms\n";
}
-- java ---
import java.util.*;
class Test {
Test (int c) {count = c;}
int count;
public static void main(String[] arg) {
long start = System.currentTimeMillis();
for (int i=0; i<=10000000; i++) {
Test test = new Test(i);
if (i % 5000000 == 0)
System.out.println (test);
After this and assign a new object to the 'test', the 'test' is no
longer ref to the older object.
So the older object is free to release.
Once the java VM's heap is empty, a gc() is called and done. The
memory for the older objects is free for allocation again.
In this example, the java VM calls OS' memory page allocation once and
then never need to alloc again.
}
long end = System.currentTimeMillis();
System.out.println("Time: " + (end - start) + " ms");
}
}