hk-modding / api

Hollow Knight Modding API
MIT License
226 stars 62 forks source link

Faster Reflection #124

Closed ghost closed 2 years ago

fifty-six commented 2 years ago

This is cool but I'd prefer not to rely on Unity mono internals, as-is reading from an offset isn't necessarily guaranteed to work out, but actually transmuting the handle is a bit much even more than that. There's also a fairly significant amount that can be done without internal access still. As far as direct ret goes I had some issues with that regarding not having the exact signature work out but if that works then I'd be happy to have that included.

fifty-six commented 2 years ago

If you want to use offsets, I'd be okay with the use of UnsafeUtility.GetFieldOffset as that's portable across Unity mono versions and should be effectively the same. You don't need to use the pointers though, UnsafeUtility has the ability to read at offsets already. I was half-meaning to try that at some point but I never got around to it.

ghost commented 2 years ago

No,UnsafeUtility.GetFieldOffset makes reflection slower

ghost commented 2 years ago

I found a phenomenon that the running speed of the code with the same function is very different in HKTool and MAPI

ghost commented 2 years ago

FieldInfo.DeclaringType is too slow

fifty-six commented 2 years ago

Is this GC safe?

ghost commented 2 years ago

I think yes, there should be no possibility to gc inside ReflectionHelper.AddOffset

fifty-six commented 2 years ago

Do you have any benches for this? Just want to see how significant an improvement it is first

ghost commented 2 years ago

Run instance field get/set 1000000 times Testing code: https://github.com/HKLab/ReflectionTest/blob/master/scripts/Test.cs#L112-L118 old: 198ms new: 139ms