Skip to content

Commit

Permalink
improved distance compute perf
Browse files Browse the repository at this point in the history
  • Loading branch information
eirannejad committed Dec 23, 2023
1 parent e3aa288 commit dc20957
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
11 changes: 10 additions & 1 deletion dev/MethodBinder.Tests/MethodBinderTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Runtime.InteropServices;

using Python.Runtime;

Expand Down Expand Up @@ -97,6 +96,16 @@ public void TestFooParam_2()
t = I.Foo(IntPtr.Zero, 0);
r = MethodInvoke.Invoke<Guid>(I, M, args, NoKwargs);
Assert.That(t, Is.EqualTo(r));

// Foo([Optional, DefaultParameterValue(12)] nint _1, uint _2)
args = new object[] { 0 };
var kwargs = new KeywordArgs
{
["_1"] = IntPtr.Zero,
};
t = I.Foo(_1: IntPtr.Zero, 0);
r = MethodInvoke.Invoke<Guid>(I, M, args, kwargs);
Assert.That(t, Is.EqualTo(r));
}
}
}
13 changes: 11 additions & 2 deletions src/runtime/MethodBinder.Invoke.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
namespace Python.Runtime
{
using KeywordArgs = Dictionary<string, object?>;
using TypeDistMap = Dictionary<int, uint>;

#if UNIT_TEST
public static class MethodInvoke
Expand All @@ -23,6 +24,8 @@ internal partial class MethodBinder
static readonly Type UNINT = typeof(nuint);
static readonly Type NINT = typeof(nint);

static readonly TypeDistMap s_distMap = new();

private sealed class MatchArgSlot
{
readonly ParameterInfo _paramInfo;
Expand Down Expand Up @@ -225,13 +228,17 @@ static uint GetDistance(Type from, Type to)
{
uint distance;

int key = from.GetHashCode() + to.GetHashCode();
if (s_distMap.TryGetValue(key, out uint dist))
{
return dist;
}

if (from == to)
{
distance = 0;
}
else if (from.IsAssignableFrom(to))
//|| CanCast(from, to)
//|| CanCast(to, from))
{
distance = 1;
}
Expand All @@ -244,6 +251,8 @@ static uint GetDistance(Type from, Type to)
);
}

s_distMap[key] = distance;

return distance;
}

Expand Down

0 comments on commit dc20957

Please sign in to comment.