Avoiding allocations in jacobian system

Why is the below function allocating, and how can I optimize it so it does not allocate?

β = 100
S(x) = 1/(1+exp(-β*x))
S_prime(x) = β*S(x)*(1-S(x))

function jacobian_system(u, p, n)
    ω, ω_A, A = p
    x, y, s = u

    return @SMatrix [
        1 - 3x^2 - y^2 + S_prime(x)   ω - 2x*y    -A * ω_A * cos(ω_A * s)
        -ω - 2x*y                     1 - x^2 - 3y^2                0
        0                              0                            0
    ]

end

test_u = [0.5, -1.7, 100.0]
test_p = [2pi, 2pi, 10.]
@btime jacobian_system(test_u, test_p, 3)

Output:

1.758 μs (20 allocations: 448 bytes)

By not including S_prime(x) the output is:

59.299 ns (1 allocation: 80 bytes)

This is probably a benchmarking artefact due to the use of globals. It should disappear when you interpolate these variables into @btime

1 Like

This is a global variable, not only for benchmarking.

4 Likes