# Understanding allocations - function returned by function

**URL:** <https://discourse.julialang.org/t/understanding-allocations-function-returned-by-function/106661>\
**Category:** New to Julia\
**Created:** [November 24, 2023, 6:17am UTC](https://discourse.julialang.org/t/understanding-allocations-function-returned-by-function/106661 "2023-11-24T06:17:15Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ysfoo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ysfoo/32/51058_2.png) [@ysfoo](https://discourse.julialang.org/u/ysfoo)\
**Post date:** [November 24, 2023, 6:17am UTC](https://discourse.julialang.org/t/understanding-allocations-function-returned-by-function/106661/1 "2023-11-24T06:17:15Z")

</div>

I’m trying to understand why executing a function that has been created by a function causes extra allocations. Example:

```julia
# 2 allocations
function make_func()
	function my_func(x)
		val = 1.23
		return val + x
	end
	return my_func
end

func = make_func()

time_func(x) = @time func(x)
func(4.56);
time_func(4.56)

# 0 allocations
function my_func2(x)
	val = 1.23
	return val + x
end

time_func2(x) = @time my_func2(x)
my_func2(4.56);
time_func2(4.56)

```

Could someone please explain why the first version of the code creates allocations? Also, how could I avoid this when I am defining a function within a function?

I’ve tried using @btime instead of @time, and the first version still gives 1 allocation.

---

<div class="post-metadata">

**Author:** ![GunnarFarneback](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gunnarfarneback/32/1827_2.png) [@GunnarFarneback](https://discourse.julialang.org/u/GunnarFarneback)\
**Post date:** [November 24, 2023, 6:50am UTC](https://discourse.julialang.org/t/understanding-allocations-function-returned-by-function/106661/2 "2023-11-24T06:50:59Z")

</div>

The performance tip about avoiding non-`const` global variables also applies to variables holding functions. Try

```julia
const func = make_func()

```
