didi@alpha ~/speedTest $ time java SpeedTest
Finisched with 2000000000 loops
real 0m16.606s
user 0m16.233s
sys 0m0.264s
didi@alpha ~/speedTest $ time ./speed
Finisched with 2000000000 loops
real 2m7.950s
user 2m6.292s
sys 0m0.180s
Here are the programms:
The c++ one
1:
2: #include iostream
3:
4: class MathObject {
5: public:
6: MathObject(){}
7: };
8:
9: int main()
10: {
11: for(int i=0; i < 2000000000 ;++i){
12: MathObject *mathObject = new MathObject();
13: delete mathObject;
14: }
15:
16: std::cout << "Finisched with 2000000000 loops" << std::endl;
17: return 0;
18: }
The Jave one
1: public class MathObject
2: {
3: public MathObject(){}
4: }
5:
6: public class SpeedTest
7: {
8: public static void main(String[] args)
9: {
10: for(int i=0; i < 2000000000 ;++i){
11: MathObject mathObject = new MathObject();
12: mathObject = null;
13: }
14: System.out.println("Finisched with 2000000000 loops");
15: }
16: }
I assume, this is because the java jvm can only change a pointer for the new Obj but c++ has to scan through the heep to find a new memory address and becomes so much slower through doing so. So java is faster at some stuff.
Download the files under : http://www.ribalba.de/speedTest.zip
2 comments:
Didi, you need to put code in <pre&rt; tags so I can read them. I find this hard to believe as the heap will not become fragmented because each new object is of the same size. Perhaps its the way malloc works in linux? Java will be doing the same. It _HAS_ to allocate for the object just like C++ does. Also it cannot decide that the old object ref is defunct until another overwrites it, so that means the heap size will be atleast twice the size of the object size (assuming it can reclaim the old heap space).
Fixed the pre stuff blogger del it when it spell checks.
I have no other idea why this could be so. I ran 10 test runs under
didi@alpha ~ $ uname -a
Linux alpha 2.6.17-gentoo-r8 #15 SMP Tue Nov 28 00:48:08 GMT 2006 x86_64 AMD Athlon(tm) 64 X2 Dual Core Processor 3800+ AuthenticAMD GNU/Linux
Post a Comment