2

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>
2
  • Either looking at the IL, or (easier) using IL Spy to see the IL as C# can illuminate what the compiler is doing. In this case I would expect something close to a no-op for an up cast (to `Class1 in you first code block). A down cast, as in your second example, does require a runtime check. (This is all based on the CLR behaviour, not F# specific). Commented May 6 at 8:10
  • Thanks, I can see that I have made a code error in my example. I know it normally require a runtime check, but have compiler writing experience and there is corner cases where something done at run time sometimes can be eliminated at compile time. Commented May 6 at 9:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.