Understanding allocations - function returned by function

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

# 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.

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

const func = make_func()
5 Likes