Linker vs Backing Fields

It’s been a while since I blogged about the MonoTouch linker. It has mostly remain unchanged since the initial updates from Xamarin – but quite a few things will be coming up in the next releases.

The first is how the linker now handles the backing fields that monotouch.dll uses to keep managed references around (and stop the GC from collecting them as long as an associated native instance exists).

Note: Everything below is internal to monotouch.dll – i.e. it doesn’t change how the linker will process user code. It’s also subject to change in the future (e.g. GC changes) but here’s some food for the curious minds…

The pattern, which is near-identical to MonoMac, looks like:

object __mt_WeakDelegate_var; // that's our backing field!
public virtual NSObject WeakDelegate {
    [Export ("delegate", ArgumentSemantic.Assign)]
    get {
        NSObject ret = ...;
        __mt_WeakDelegate_var = ret;
        return ret;
    [Export ("setDelegate:", ArgumentSemantic.Assign)]
    set {
        call (value.Handle);
        __mt_WeakDelegate_var = value;

The linker is already able to remove the property getter and the setter when they are not used anywhere – but what about the backing field ? The linker can remove fields, right ?

Of course the linker can remove fields – but only when it’s not used elsewhere. But since the field real type (NSObject in this example) implements IDisposable it will also be used in the type Dispose method – and that makes it unavailable to be linked away… until now (or soon).

And what does it give me ?

In the case of Touch.Unit this means 203 backing fields can be removed, along with the code that used them in the Dispose methods.

That’s not a huge gain, application size-wise, but honestly the most interesting gain is that each instance of those MonoTouch.* types now has a smaller memory footprint. If a field was saved it’s because the type itself could not be removed from the application (so it’s likely used). So the more you create the more you save 😉


About spouliot

Xamarin Hacker, Mono Contributor, Open Source Enthusiast with strong interests in Code Analysis, Cryptography and Security. Presently working on MonoTouch, previous projects were Moonlight and libgdiplus and a lot of the cryptographic work done on Mono.
This entry was posted in linker, mono, monotouch, xamarin. Bookmark the permalink.

One Response to Linker vs Backing Fields

  1. Pingback: Linker vs Bindings and NewRefcount | surprisingly unimpressed

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s