I am currently reading through the F# core library source code and stumbled upon a common pattern which made me wonder a little about the performance of it, and could not find anything about it by a quick web search.
The pattern:
type Class1() = ...
type Class2() =
inherit Class1()
let inline asClass1 t = t :?> Class1
I have included a specific examples from F# source code below.
My question about this pattern. Is there any optimization done by the compiler in respect to the downcast i.e. can the compiler decide that the downcast always result in the same type, or is it just a "readability" or common pattern factorization pattern?
If no optimization then why split the underlying types of Map and Set up?
Specific example Set
[<NoEquality; NoComparison>]
[<AllowNullLiteral>]
type internal SetTree<'T>(k: 'T, h: int) =
member _.Height = h
member _.Key = k
new(k: 'T) = SetTree(k, 1)
[<NoEquality; NoComparison>]
[<Sealed>]
[<AllowNullLiteral>]
type internal SetTreeNode<'T>(v: 'T, left: SetTree<'T>, right: SetTree<'T>, h: int) =
inherit SetTree<'T>(v, h)
member _.Left = left
member _.Right = right
let inline private asNode (value: SetTree<'T>) : SetTreeNode<'T> =
value :?> SetTreeNode<'T>