drujensen / fib

Performance Benchmark of top Github languages

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Python: Another version

jdbctracer opened this issue · comments

Would it be possible to use a slightly different coding style?

def fib(n):
    return 1 if n <= 1 else fib(n - 1) + fib(n - 2)

It makes a noticable difference on my machine without beeing much different from the original.

Hi @jdbctracer I was trying to keep them all the same and use a guard instead of else condition. Both crystal and ruby versions are using the trailing if.

What about:

def fib(n):
    return 1 if n <= 1
    return fib(n - 1) + fib(n - 2)

It makes a noticeable difference on my machine

As in a performance difference? I wonder why. Seems like a guard would be just as fast.

Pythons primary cost is in the instruction count, and the single line version generates different opcodes than guards (specifically less), in addition it 'might' even be faster still if the condition and the cases were inverted on the single line version as well.

TIL if then else is faster than if return in python because it generates less opcodes. Is this the case in other interpreted languages as well?

Is this the case in other interpreted languages as well?

Not actually sure, python's the only opcode backend I've worked with so far aside from my own languages for interpreted languages (thus ignoring Java and so forth opcode work).

For my small test the difference was around 9%.
I would guess that other languages could exhibit the same behaviour:
less opcodes -> more dense presentation of intent -> more optimized implementation
Keep in mind, that there is less infrastructure at runtime, no opcode rearrangement takes place.

@jdbctracer Precisely, but I wouldn't expect every language's opcode to be as 'high-level' as Python's is (which is pretty expressive for an opcode set), so others may not get quite as many boosts but I'd still expect a little.