# Performance of persistent variables

**URL:** https://discourse.julialang.org/t/performance-of-persistent-variables/112044
**Category:** Performance
**Tags:** metaprogramming, compilation, preallocation
**Created:** [March 24, 2024, 4:33pm UTC](https://discourse.julialang.org/t/performance-of-persistent-variables/112044 "2024-03-24T16:33:09Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![c\_sell](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/c_sell/32/38854_2.png) [@c\_sell](https://discourse.julialang.org/u/c_sell)
#### Post date: [March 24, 2024, 4:33pm UTC](https://discourse.julialang.org/t/performance-of-persistent-variables/112044/1 "2024-03-24T16:33:09Z")

</div>

Hello,  
I have a simple toy example in which I compare two methods of creating persistent variables. In my case, both methods exhibit identical performance.

Are there any differences to consider regarding safety, compile times, or performance?

The code:

```julia
using BenchmarkTools
macro persistent(init)
    var = gensym()
    eval(:(const $var = $init))
    quote
        $var
    end
end

function exp_function(n::Int) #expensive function to call
    rng = MersenneTwister(n)
    A = zeros(n,n)
    for i in 1:n,j in 1:n
        A[i,j] = sum(rand(rng,i,j).-0.5)
    end
    return A
end

function foo1() #version 1
    A = @persistent exp_function(50)
    return sum(A)
end

@generated function foo2() # version2
    A = exp_function(50)
    return :(sum($A))
end

```
