gkreidl,

I call that stupid programming.

It's not stupid programming. It's a benchmark. It's often used measure of the efficiency of making function calls, with a bit of arithmetic thrown in for good measure.

You are right that no one in their mind would calculate Fibonacci numbers that way in a real application.

On the other hand your fibo2 in Python is stupid programming as well, it's down right buggy. It is growing the array farr up to the size of n. If n is big it's going to run out of memory!

Also it includes the timing of printing the result in the reported execution time.

This is better:

Code: Select all

```
import time
def fibo2(n):
farr = [1,1]
for i in range(0,n-1):
farr.append(farr[i]+farr[i+1])
return farr[n-1]
for runs in range (0, 9):
t = time.time()
f = fibo2(42)
diff = time.time() - t
print f
print diff
```

With timing like so:

Code: Select all

```
$ python fibo2.py
267914296
0.000155925750732
267914296
0.000159978866577
267914296
0.000154972076416
267914296
0.000144004821777
267914296
0.000143051147461
267914296
0.000144004821777
267914296
0.000144004821777
267914296
0.000144004821777
267914296
0.000142097473145
```

of course that is still slow. We can make the JS equivalent:

Code: Select all

```
function fibo2(n) {
let farr = [1, 1];
for (let i = 2; i < n; i++) {
farr[i] = farr[i - 1] + farr[i - 2];
}
return farr[n - 1];
}
for (let runs = 0; runs < 10; runs += 1) {
let time = process.hrtime();
let f = fibo2(42);
let diff = process.hrtime(time);
console.log(f);
console.log(diff[0] + diff[1] * 1e-9);
}
```

With timing like so:

$ node fibo2.js

[/code]

267914296

0.002088786

267914296

0.000287393

267914296

0.00008401

267914296

0.000089843

267914296

0.000079114

267914296

0.00007552000000000001

267914296

0.000079739

267914296

0.00007942600000000001

267914296

0.00007624900000000001

267914296

0.000073905

[/code]

Which is basically twice as fast.

Note how node.js takes a few iterations of fibo2 to "warm up". That's OK our programs generally run for long periods.

Of course the proper way to do a fast fibo is to just keep two variables holding the last two numbers in the sequence. That is another ten times faster in JS, probably Python too. And does not blow up memory consumption.

I leave that as an exercise for the reader

Memory in C++ is a leaky abstraction .