I was doing a bit of doodling, comparing performance of python to node.js to java today and thought I’d do this by creating a program that hunts down hailstone sequences with a high number of terms.
The hailstone algorithm is defined by the function h(n) where n can be any positive integer
h(n) = n/2 if n is even or 3n + 1 if n is odd
A sequence is created by taking the last h(n) and re-inserting into the formula
A hailstone sequence repeats once n reduces to 1 (becoming 1, 4, 2, 1…)
I decided to define my sequence as ending once the first 1 was found and then count the terms that it took to find 1. My interest was finding hailstones with a large number of terms by iterating through all known integers.
So for example H(6) = 6, 3, 10, 5, 16, 8, 4, 2, 1
My code would generate H(6) has 9 terms
I wrote a finder that would continue to search for the next highest number of terms.
Here’s a sample of the output it delivers
Hailstone (1)=4 terms (calcTime=121354 microseconds)
Hailstone (3)=8 terms (calcTime=48493 microseconds)
Hailstone (6)=9 terms (calcTime=28796 microseconds)
Hailstone (7)=17 terms (calcTime=74927 microseconds)
Hailstone (9)=20 terms (calcTime=129867 microseconds)
Hailstone (18)=21 terms (calcTime=79760 microseconds)
Hailstone (25)=24 terms (calcTime=863670 microseconds)
Hailstone (27)=112 terms (calcTime=814249 microseconds)
Hailstone (54)=113 terms (calcTime=198646 microseconds)
Hailstone (73)=116 terms (calcTime=204504 microseconds)
Hailstone (97)=119 terms (calcTime=93431 microseconds)
Java jvm on this test outshone node.js and python. I was expecting python to outperform node.js but node took the trophy as the fastest interpreted language on the test.
Not super scientific but nice example of comparative performance for this example.
Update: Using PyPy JIT compilation for python gets performance on a par or slightly better than node.js, but both continue to underperform java performance significantly