29 May 2009

Python is faster than Java!

I wanted to pitch Java and Python against each other and see how they perform. So I put in a simple program that puts some stress on the system. Data Structures would also be used. Both the programs should be run on same machine. There shouldn't be any other Java or Python process running in background. I wrote a simple program in both Java and Python and ran them.

Java Program (JVM version - 1.6.0_11-b03)

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;


public class PerformanceTester {

private final static int SIZE = 500000;

public static void main(String[] args) {

long start_time = System.currentTimeMillis();

Hashtable build_hash = new Hashtable();
for(int i=0; i build_array = new ArrayList();
for(Iterator it = build_hash.keySet().iterator(); it.hasNext();){
Integer value = build_hash.get(it.next());
it.remove();
String strValue = (value.intValue()+8)+"add more";
build_array.add(strValue);
}

long stop_time = System.currentTimeMillis();
System.out.println("Total Time = "+((stop_time - start_time)/1000.0000));

}

}


Multiple Run Result
Total time = 1.391
Total time = 1.375
Total time = 1.344
Total time = 1.422
Total time = 1.484


Python Program (CPython version 2.6.1)

import time

start_time = time.clock()
SIZE = 500000

build_hash = {}

for a in range(1,SIZE):
build_hash[str(a)] = a

build_array = []

for key in build_hash:
build_array.append(str(build_hash[key]+8) + "add more")
build_hash[key] = None

stop_time = time.clock()
print "total time = ", (stop_time - start_time)


Multiple Run Result

Total time = 0.888883333612
Total time = 0.878249380963
Total time = 0.991458537034
Total time = 0.850523498354
Total time = 0.860505161151

I see Python showing a huge advantage when it comes to speed of execution. Java is slow! Thats bad news for Java. I would like you to try same or similar program and let me know how it performs. If you run the same above programs, try increasing the hash size for both the programs. You will be surprised with what you see! I can't believe Java is not only slow, but also uses more memory. Python is not only simpler, but faster, more powerful and uses lesser memory than Java.

No comments:

Post a Comment