# What do allocations (triggering GC) depend on?

**URL:** <https://discourse.julialang.org/t/what-do-allocations-triggering-gc-depend-on/114202>\
**Category:** General Usage\
**Tags:** gc, staticcompiler, statictoolsjl\
**Created:** [May 13, 2024, 2:20pm UTC](https://discourse.julialang.org/t/what-do-allocations-triggering-gc-depend-on/114202 "2024-05-13T14:20:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Thomas008](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/thomas008/32/204169_2.png) [@Thomas008](https://discourse.julialang.org/u/Thomas008)\
**Post date:** [May 13, 2024, 2:20pm UTC](https://discourse.julialang.org/t/what-do-allocations-triggering-gc-depend-on/114202/1 "2024-05-13T14:20:27Z")

</div>

I want to compile code with help of StaticCompiler. So I need to avoid GC allocations.  
I want to understand when GC allocations occur. In the following code 3 GC allocations happen:

```julia
using StaticTools

mutable struct D

  t::MallocArray{Int64}

  function D()
    t = MallocArray{Int64}(undef,1)
    new(t)
  end

end

function str2num(str::MallocString)::Int64
  len = length(str)
  zahl = 0
  for i in 1:len
    zahl += (Int(str[i])-64) * 26 ^ (len-i)
  end
  zahl 
end

function g(d::D,r::Int64,str::MallocString)
  idx = r * 1 + 0
  d.t[idx] = str2num(str)
end

function f()
  d = D()  
  g(d,1,m"A")
  0
end

@time f()

```

Under some conditions no GC allocations occur:

If there is only a `+` or a `*` in `g()`, then no GC allocation occur:  
`idx = r * 1` or  
`idx = r + 0`

If there is no struct, then no GC allocations occur: Use the code above, omit the struct `D` and modify `g()` and `f()` to:

```julia
function g(t::MallocArray,r::Int64,str::MallocString)
  idx = r * 1 + 0
  t[idx] = str2num(str)
  t
end

function f()
  t = MallocArray{Int64}(undef,1)
  t = g(t,1,m"A")
  0
end

```

Considerung function `str2num()`, when there is no `Int()`, then no GC allocations happen:

`zahl += (Int(65)-64) * 26 ^ (len-i)`

Similarly, when in `str2num()` there is no for-loop, or at least there is no variable in the number of iterations, then there are no GC  
alocations:

```julia
  zahl = 0
  i = 1
  zahl += (Int(str[i])-64) * 26 ^ (len-i)

```

or

```julia
  for i in 1:1
    ...
  end

```

When do GC allocations occur?

---

<div class="post-metadata">

**Author:** ![sgaure](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sgaure/32/14779_2.png) [@sgaure](https://discourse.julialang.org/u/sgaure)\
**Post date:** [May 13, 2024, 4:28pm UTC](https://discourse.julialang.org/t/what-do-allocations-triggering-gc-depend-on/114202/2 "2024-05-13T16:28:18Z")

</div>

It typically allocates when using mutable structs. Under 1.10.3 allocations go away if the `D` struct is immutable. Under 1.12-DEV it does not allocate with a mutable struct either.
