Huge performance drop using @spawn

Using Jeff’s article https://julialang.org/blog/2019/07/multithreading

using
julia> VERSION
v"1.3.1"
I simply tried the first example with JULIA_NUM_THREADS=4 on a 12 core machine with 64GB RAM

import Base.Threads.@spawn

function fib(n::Int)
    if n < 2
        return n
    end
    t = @spawn fib(n - 2)
    return fib(n - 1) + fetch(t)
end

julia> @btime fib(20)
4.473 ms (93843 allocations: 8.11 MiB)
6765

While running the same without @spawn we get
julia> @btime fib(20)
26.614 μs (0 allocations: 0 bytes)
6765

Conclusion using @spawn just brings huge counter perf and heavy memory usage.

Can anyone clarify for me please why
Thanks

The problem is that almost all of the calls fib makes are to fib(1) and fib(2). Since spawn has about a 1 msec time, you would only want to use it when the inside computation takes more than that amount of time.

I get the Point Oscar, thks for you immediate reply :wink:

See also this as it was already discussed in detail!

tl;dr start using spawn only with big enough ns.