# Performance drawback with subtyping

**URL:** <https://discourse.julialang.org/t/performance-drawback-with-subtyping/51939>\
**Category:** Performance\
**Created:** [December 16, 2020, 4:02pm UTC](https://discourse.julialang.org/t/performance-drawback-with-subtyping/51939 "2020-12-16T16:02:42Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [December 16, 2020, 5:27pm UTC](https://discourse.julialang.org/t/performance-drawback-with-subtyping/51939/6 "2020-12-16T17:27:59Z")

</div>

> [@Ronneesley](#):
>
> Thanks for you answer. But with type parameter I’ve only one type of Line at `lines` attribute. I need both, lines type A, B, etc.

If you only need a few types, you probably want something like

```julia
struct Picture
   lines :: Vector{Union{LineA,LineB}}
end

```

still that can come with performance problems, because if you define a method that acts on these types, and you dispatch on this vector at run time, the dynamic dispatch will have a performance penalty. If you have many types, probably you will need some of the ideas that were dicussed in these threads, because at the end they ended up in a discussion of exactly that problem:

> [@Disabling allocations](https://discourse.julialang.org/t/disabling-allocations/51028/51):
>
> Very interesting. Using a simple eval did the trick: abstract type Material end struct Material1 \<: Material m :: Float64 end struct Material2 \<: Material m :: Float64 end struct HitPoint{T \<: Material} p :: Float64 r :: Float64 m :: T end # the hit function hit(p \<: HitPoint) = p.r\*p.p\*p.m.m # generate functors for each type for T in subtypes(Material) eval(:((p::HitPoint{$T})() = p.r\*p.p\*p.m.m)) end # naive sum function hits(hitpoints) s = 0. for p in hitpoints s +=…

A related follow up is here:

> [@Macro to write function with many conditionals](https://discourse.julialang.org/t/macro-to-write-function-with-many-conditionals/51616/5):
>
> Great that that had been done. I will see if I understand that implementation.

(and I wrote a simple example here, but I have yet to write it in detail: [https://m3g.github.io/JuliaCookBook.jl/stable/splitting/](https://m3g.github.io/JuliaCookBook.jl/stable/splitting/)

---

_[View the full topic](https://discourse.julialang.org/t/performance-drawback-with-subtyping/51939)._
