Please help me solve a benchmark question about Elixir vs. Ruby performance.
I tried to implement the same factorial in both languages, and Ruby shows better results than Elixir:
# ruby_factorial_with_iterator.rb
def factorial_with_iterator(n)
res = 1
(1..n).each{|time| res *= time}
res
end
p "factorial_with_iterator(200000)"
p factorial_with_iterator(200000)
After run:
$ time ruby ruby_factorial_with_iterator.rb
real 0m18.378s
user 0m17.348s
sys 0m0.844s
and two Elixir examples:
# elixir_factorial_with_iterator.exs
defmodule FactorialWithIterator do
def of(n) do
Enum.reduce(1..n, 1, &*/2)
end
end
IO.puts "Factorial of 200000: "
IO.puts FactorialWithIterator.of(200000)
After run:
$ time elixir elixir_factorial_with_iterator.exs
real 1m1.735s
user 1m1.556s
sys 0m0.104s
Another example:
# elixir_factorial_with_recursion.exs
defmodule FactorialWithRecursion do
def of(0), do: 1
def of(n) when n > 0 do
n * of(n - 1)
end
end
IO.puts "Factorial of 200000: "
IO.puts FactorialWithRecursion.of(200000)
After run:
$ time elixir elixir_factorial_with_recursion.exs
real 1m7.149s
user 1m6.248s
sys 0m0.092s
Why is there such a huge difference: Elixir - 1m1s, and Ruby - just 18s? Or how to write correct iteration code in the Elixir?
P.S. Environment:
- Ubuntu 16.04
- ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]
- Erlang/OTP 19 [erts-8.3] [source-d5c06c6] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]
- Elixir 1.4.4