Allocations for type assertions

In the below code snippet

something::ConcreteType = mydict[key] ###mydict = Dict{String,AbstractType}()

the LLVM IR shows a call to ijl_gc_pool_alloc and from the labelling, it looks like that’s part of the type assertion on the LHS of the snippet. What is the rationale for the allocation and what can I do to avoid it if know the returned object is definitely a ConcreteType ? Is type assertion always allocating?

It’s likely the retrieval from the dict that allocates intermediary storage, not the type assertion. The objects from the dict are only known to be of an abstract type after all.

1 Like

If the dict values are already boxed and heap-allocated, why does retrieval cause another allocation?

I’m not 100% sure on this, but it may have to do with the value needing to be rooted when returned from the function/passed to convert (which indeed would be for the conversion) :thinking: It’s admittedly a bit hard to diagnose the exact cause of an allocation, but in this case it’s definitely due to the abstractly typed values in the dict.

As for avoiding that allocation - type instabilities like that unfortunately cause allocations all over the place, since now you need to keep values boxed (and more importantly, GC rooted) when passing them between functions. So even if the value returns from the function, it needs to be boxed, because the overall type can only be assumed to be Real.

For more direct diagnosis though, you’ll have to provide an example with more context; there’s just too many possible ways to progress here to diagnose from just a single conversion & dict indexing.

1 Like

When you type assert the variable, it will try to convert the RHS to the type of the variable. If you know the RHS type you may instead want to type assert the RHS:

something = mydict[key]::ConcreteType