#!/bin/bash
: <<'EOF'
Dumb Fibonacci microbenchmark.  See dumbfib.S.

Since shell functions don’t really have return values any more than
assembly-language subroutines do, I’ve taken the liberty of putting
the “return value” in a shell variable instead of echoing it to
standard output, as is traditional.  That’s because doing it the
traditional way involves forking a subprocess, which is just
unreasonably slow, and easily avoidable if you have such a performance
problem in a shell script.

From a previous version of this I got

    fib(30) = 832040

in 42.6 seconds, and then when I restarted with fib(40):

    fib(40) = 102334155

in 95'22" the first time and 95'46" the second, which is 8400× slower
than dumbfib.S.

Running such things in `dash` (using `[` rather than `[[`) reveals
that it runs several times faster than bash, while mksh is in between.
See dumbfib.sh.  In `bash` using `[` causes about a 15% slowdown.

EOF

_fib() {
    if [[ "$1" -le 2 ]]; then
        rv=1
    else
        _fib $(($1 - 1))
        local f1=$rv
        _fib $(($1 - 2))
        rv=$(($f1 + $rv))
    fi
}

fib() {
    _fib "$@"
    echo "$rv"
}

n=30
echo "fib($n) = $(fib "$n")"
