In my previous post I compared I/O and string formating and python was better than Java. Anyway as Java have primitive types and do not need to box/unbox variables it could be realy faster than python. Here is an exemple where I compute the distances between 3D points.

### The python code

import time from numpy import * from math import * n = 1000000 v1 = zeros(n*3) v2 = zeros(n*3) dn = double(n) for i in xrange(n): v1[i] = 1.0 + i / dn; v2[i] = 2.0 + i / dn; r = zeros(n) t1 = time.time() for i in xrange(n/3): for j in xrange(3): r[i]=r[i] + (v1[i*3+j]-v2[i*3+j])**2 r[i]=sqrt(r[i]) t2 = time.time() print t2-t1

### The Java code

public static void main(String[] argv) { int n = 1000000; double[] v1 = new double[n*3]; double[] v2 = new double[n*3]; for(int i = 0; i < n; i++) { v1[i] = 1.0+i/(double)n; v2[i] = 2.0+i/(double)n; } double[] r = new double[n]; double tmp; long t1 = System.nanoTime(); for(int i = 0; i < n/3; i++) { for(int j = 0; j < 3; j++) { tmp = v1[i*3+j]-v2[i*3+j]; tmp = tmp*tmp; r[i] += tmp; } r[i] = Math.sqrt(r[i]); } long t2 = System.nanoTime(); System.out.println("time: "+(t2-t1)/1E9); for(int i = 0; i<n; i++) { System.out.println(r[i]); } }

### Results

- Java: 0.02s (with a precision of 0.05s)
- Python: 9.49s

### Conclusion

There are probably ways to improve my python code using numpy a better way, but most of the time to get rid of boxing/unboxing time you will have to write C code to speedup most critical part of algorithms. While Python is only a gluing (yet very good) technology, Java can be used to write fast low level algorithms.