xamarin / xamarin-macios

.NET for iOS, Mac Catalyst, macOS, and tvOS provide open-source bindings of the Apple SDKs for use with .NET managed languages such as C#
Other
2.47k stars 512 forks source link

[RFC] Possibly port IsDirectBinding optimization to Mac #6046

Open Therzok opened 5 years ago

Therzok commented 5 years ago

Currently, there is no safe way to directly remove IsDirectBinding for Mac, unless the Dynamic registrar is completely removed and/or assembly loading.

I was wondering whether we could alleviate the costs here by creating 2 different SelectorInvoker classes, let's call them DirectInvoker and SubclassInvoker.

They would be a really thin layer over the Messaging calls, where DirectInvoker would call msgSend, SubclassInvoker would call msgSendSuper, both classes being sealed to avoid virtual calls at JIT time, all the methods being marked as aggressive inlining. Static readonly instances could be defined which are then used by NSObject.

As an example, SetValueKeyForPath esentially becomes this;

class NSObject
{
    SelectorInvoker invoker; // set it in InitializeObject

    public void SetValueForKeyPath (IntPtr handle, NSString keyPath)
    {
        if (keyPath == null)
            throw new ArgumentNullException ("keyPath");

        invoker.void_objc_msgSend_IntPtr_IntPtr (this.Handle, selSetValue_ForKeyPath_Handle, handle, keyPath.Handle);
    }    
}

At object construction time, we would take a 8byte memory hit for each NSObject at the price of removing branch prediction on every call. In an ideal world, direct calls would be generated by Mono, so we would have the performance improvement of what ILLinker would do at the price of slightly increased object size.

Given desktop does not have the same limitations memory wise as iOS, it seems like a decent enough trade-off to me. Maybe an experiment could be done in this sense?

spouliot commented 5 years ago

Not sure I fully follow but

The approach above would

But it's an interesting approach. We should get numbers to see how much this would impact (negatively/memory vs positively/performance) applications that cannot use the managed linker (like VS4M).

Therzok commented 5 years ago

@spouliot yes, the scenario I was thinking of supporting was clearly VSMac.