-
-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(perf): use compiled lambda activator
- Loading branch information
1 parent
f70ea2d
commit 55ad31e
Showing
3 changed files
with
131 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
using System; | ||
using System.Linq.Expressions; | ||
using System.Reflection; | ||
|
||
namespace IGDB.Serialization | ||
{ | ||
/// <summary> | ||
/// See: https://rogerjohansson.blog/2008/02/28/linq-expressions-creating-objects/ | ||
/// </summary> | ||
public static class LambdaActivator | ||
{ | ||
public delegate object ObjectActivator(params object[] args); | ||
|
||
public static ObjectActivator GetActivator(ConstructorInfo ctor) | ||
{ | ||
ParameterInfo[] paramsInfo = ctor.GetParameters(); | ||
|
||
ParameterExpression param = | ||
Expression.Parameter(typeof(object[]), "args"); | ||
|
||
Expression[] argsExp = | ||
new Expression[paramsInfo.Length]; | ||
|
||
for (int i = 0; i < paramsInfo.Length; i++) | ||
{ | ||
Expression index = Expression.Constant(i); | ||
Type paramType = paramsInfo[i].ParameterType; | ||
|
||
Expression paramAccessorExp = | ||
Expression.ArrayIndex(param, index); | ||
|
||
Expression paramCastExp = | ||
Expression.Convert(paramAccessorExp, paramType); | ||
|
||
argsExp[i] = paramCastExp; | ||
} | ||
|
||
NewExpression newExp = Expression.New(ctor, argsExp); | ||
|
||
LambdaExpression lambda = | ||
Expression.Lambda(typeof(ObjectActivator), newExp, param); | ||
|
||
ObjectActivator compiled = (ObjectActivator)lambda.Compile(); | ||
return compiled; | ||
} | ||
} | ||
} |