I have a very similar issue that I think fits with what the OP is saying, so I will post here instead of starting a new thread (obviously feel free to tell me that I should move this to a new thread).
The problem has to do with seeing more allocations when accessing a function that is inside a struct than when using the same function directly. Please consider the following MWE. The function in question is tanh. In function first(), tanh is called directly. In function second() it is called from within struct dummy. Function third() is calls tanh from a struct where no type has been provided.
I hope the following code makes it clearer:
struct Dummy
f::Function
end
struct DummyNoType
f
end
function runme()
a = randn(1000)
dummy = Dummy(tanh)
dummynotype = DummyNoType(tanh)
v = 0.0
function first()
for i in 1:1000
v += tanh(a[i])
end
end
function second()
for i in 1:1000
v += dummy.f(a[i])
end
end
function third()
for i in 1:1000
v += dummynotype.f(a[i])
end
end
@time first()
@time second()
@time third()
end
If execute run() I get:
0.000057 seconds (2.00 k allocations: 31.250 KiB) # called first()
0.000081 seconds (3.00 k allocations: 46.875 KiB) # called second()
0.000089 seconds (3.00 k allocations: 46.875 KiB) # called third()
Why does the call to second() result in more memory allocations? Thanks for reading this.