Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize reflection of F# types #9714

Merged
merged 1 commit into from
Jul 23, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/fsharp/FSharp.Core/reflect.fs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ open Microsoft.FSharp.Core.Operators
open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators
open Microsoft.FSharp.Collections
open Microsoft.FSharp.Primitives.Basics
open System.Linq.Expressions

module internal ReflectionUtils =

Expand Down Expand Up @@ -63,6 +64,19 @@ module internal Impl =
| null -> None
| prop -> Some(fun (obj: obj) -> prop.GetValue (obj, instancePropertyFlags ||| bindingFlags, null, null, null))

let compilePropGetterFunc (prop: PropertyInfo) =
let param = Expression.Parameter (typeof<obj>, "param")

let expr =
Expression.Lambda<Func<obj, obj>> (
Expression.Convert (
Expression.Property (
Expression.Convert (param, prop.DeclaringType),
prop),
typeof<obj>),
param)
expr.Compile ()

//-----------------------------------------------------------------
// ATTRIBUTE DECOMPILATION

Expand Down Expand Up @@ -585,6 +599,10 @@ module internal Impl =
let props = fieldPropsOfRecordType(typ, bindingFlags)
(fun (obj: obj) -> props |> Array.map (fun prop -> prop.GetValue (obj, null)))

let getRecordReaderFromFuncs(typ: Type, bindingFlags) =
let props = fieldPropsOfRecordType(typ, bindingFlags) |> Array.map compilePropGetterFunc
(fun (obj: obj) -> props |> Array.map (fun prop -> prop.Invoke obj))

let getRecordConstructorMethod(typ: Type, bindingFlags) =
let props = fieldPropsOfRecordType(typ, bindingFlags)
let ctor = typ.GetConstructor(BindingFlags.Instance ||| bindingFlags, null, props |> Array.map (fun p -> p.PropertyType), null)
Expand Down Expand Up @@ -806,7 +824,7 @@ type FSharpValue =
static member PreComputeRecordReader(recordType: Type, ?bindingFlags) : (obj -> obj[]) =
let bindingFlags = defaultArg bindingFlags BindingFlags.Public
checkRecordType ("recordType", recordType, bindingFlags)
getRecordReader (recordType, bindingFlags)
getRecordReaderFromFuncs (recordType, bindingFlags)

static member PreComputeRecordConstructor(recordType: Type, ?bindingFlags) =
let bindingFlags = defaultArg bindingFlags BindingFlags.Public
Expand Down