Skip to content

Instantly share code, notes, and snippets.

@cisoun
Last active April 1, 2021 08:58
Show Gist options
  • Save cisoun/0ae0b45e69c4c7ee1dfb4df664876f0e to your computer and use it in GitHub Desktop.
Save cisoun/0ae0b45e69c4c7ee1dfb4df664876f0e to your computer and use it in GitHub Desktop.
Performance comparison between PHP vs Python vs Ruby

Performance comparison between PHP vs Python vs Ruby

Here's a performance comparison between PHP vs Python vs Ruby done by doing a Fibonacci sequence of 35 iterations in each language. I tried to adapt the codes in order to have the exact same behavior.

Tested versions are the following:

➜ php --version   
PHP 8.0.3 (cli) (built: Mar  4 2021 20:39:15) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.0.3, Copyright (c) Zend Technologies
    with Zend OPcache v8.0.3, Copyright (c), by Zend Technologies

➜ python --version
Python 3.8.0

➜ ruby --version
ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-darwin18]

Code

PHP: fib.php

<?php
function Fibonacci($n) {
	if ($n == 0) return 0;
	if ($n == 1) return 1;
	return (Fibonacci($n - 1) + Fibonacci($n - 2));
}
Fibonacci(35);
?>

Python: fib.py

def Fibonacci(n):
	if n == 0: return 0
	if n == 1: return 1
	return (Fibonacci(n - 1) + Fibonacci(n - 2))
Fibonacci(35)

Ruby: fib.rb

def Fibonacci(n)
	return 0 if n == 0
	return 1 if n == 1
	(Fibonacci(n - 1) + Fibonacci(n - 2))
end
Fibonacci(35)

Tests

time php ./fib.php
php ./fib.php  0,89s user 0,02s system 98% cpu 0,918 total

➜ time python fib.py
python3 fib.py  3,29s user 0,03s system 98% cpu 3,353 total

➜ time ruby ./fib.rb
ruby ./fib.rb  1,14s user 0,02s system 98% cpu 1,177 total
@cisoun
Copy link
Author

cisoun commented Apr 1, 2021

For fun:

Bash: fib.sh

#!/bin/bash
Fibonacci () {
	local n=$1
	if [[ $n -eq 0 ]]; then echo 0; return; fi
	if [[ $n -eq 1 ]]; then echo 1; return; fi
	echo $(($(Fibonacci $((n - 1))) + $(Fibonacci $((n - 2)))))
}
Fibonacci 35

I had to stop the script. It couldn't finish even after 5 minutes...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment