Comment

Comment by shakna

I couldn't find a list of the hardware used in the benchmarks, so comparing is difficult, though before testing, I'd lean towards agreeing with you. Luajit is often on par with C, D or Go.

However, as C was one of the faster, I'll use it as a comparison.

fib.c, compiled with 03: 10.49user 0.28system 0:11.62elapsed

    #include <stdio.h>

    long fib(long n) {
      if (n <= 1) return 1;
      return fib(n - 1) + fib(n - 2);
    }

    int main(void) {
      printf("%li\n", fib(46));
      return 0;
    }
Lua:

    function fib(n)
      if n <= 1 then
        return 1
      else
        return fib(n - 1) + fib(n - 2)
      end
    end

    print(fib(46))
Luajit: 48.66user 0.11system 0:52.95elapsed

Lua 5.3: 717.21user 8.40system 14:19.47elapsed

As Luajit was so much slower than C for this, which can be somewhat surprising.

Luajit would probably beat Ruby, for it's interpreted crown, but without optimisation, it won't beat the big boys.

I would say, that Lua isn't a good fit for solving this kind of problem, with these constraints, because every function call requires a hash lookup, which is irritating.

Of course, you could use Luajit's FFI to use C's implementation, which would be somewhat faster. Or expose the C implementation as a Lua library.

However, Lua is probably also a really good fit for memoization, and other techniques like that.

    local nums = {}
    local fib

    fib = function(n)
      if n <= 1 then
        return 1
      else
        if nums[n] then
          return nums[n]
        else
          nums[n] = fib(n - 1) + fib(n - 2)
          return nums[n]
        end
      end
    end

    print(fib(46))
This is a fairly naive implementation, but has the same final result as the previous examples... And 'time' is unable to measure how fast it is (Both Luajit and Lua5.3). For all intents and purposes, it's instant.
parent shakna 8 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton