# Avoiding allocations in jacobian system

**URL:** https://discourse.julialang.org/t/avoiding-allocations-in-jacobian-system/126376
**Category:** Performance
**Tags:** question, staticarrays
**Created:** [February 27, 2025, 9:39am UTC](https://discourse.julialang.org/t/avoiding-allocations-in-jacobian-system/126376 "2025-02-27T09:39:50Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![AP9](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ap9/32/212443_2.png) [@AP9](https://discourse.julialang.org/u/AP9)
#### Post date: [February 27, 2025, 9:39am UTC](https://discourse.julialang.org/t/avoiding-allocations-in-jacobian-system/126376/1 "2025-02-27T09:39:50Z")

</div>

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

```julia
β = 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:

```julia
1.758 μs (20 allocations: 448 bytes)

```

By not including S\_prime(x) the output is:

```julia
59.299 ns (1 allocation: 80 bytes)

```

---

<div class="post-metadata">

### Author: ![gdalle](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gdalle/32/27854_2.png) [@gdalle](https://discourse.julialang.org/u/gdalle)
#### Post date: [February 27, 2025, 10:21am UTC](https://discourse.julialang.org/t/avoiding-allocations-in-jacobian-system/126376/2 "2025-02-27T10:21:41Z")

</div>

This is probably a benchmarking artefact due to the use of globals. It should disappear when you [interpolate](https://juliaci.github.io/BenchmarkTools.jl/dev/manual/#Interpolating-values-into-benchmark-expressions) these variables into `@btime`

---

<div class="post-metadata">

### Author: ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)
#### Post date: [February 27, 2025, 10:26am UTC](https://discourse.julialang.org/t/avoiding-allocations-in-jacobian-system/126376/3 "2025-02-27T10:26:06Z")

</div>

> [@AP9](#):
>
> `β = 100`

This is a global variable, not only for benchmarking.
