Linker vs Bindings and IsDirectBinding

If you looked at my previous entries related to the linker and bindings: NewRefcount, UI thread checks, Runtime.Arch or at MonoTouch‘s generated bindings source code then you likely noticed another common pattern, e.g.

	[Export ("sizeToFit")]
	[CompilerGenerated]
	public virtual void SizeToFit ()
	{
		global::MonoTouch.UIKit.UIApplication.EnsureUIThread ();
		if (IsDirectBinding) {
			Messaging.void_objc_msgSend (this.Handle, selSizeToFit);
		} else {
			Messaging.void_objc_msgSendSuper (this.SuperHandle, selSizeToFit);
		}
	}

The use of IsDirectBinding (line #6) is a bit less common in third party bindings, unless the -e option was used with btouch to allow types to safely inherit from your bindings. The fact that such an option exists is a sign that we’d like to get rid of this condition when it’s not required.

If we knew that a type is never subclassed then we could remove the IsDirectBinding (line #6) as its value would be constant, true, and that would also allow the removal of the false branch (line #9).

Along with some previous optimizations that can remove [CompilerGenerated] (line #2) and EnsureUIThread (line #5), we would end up with a smaller, branchless method that simply calls the right selector, like this:

	[Export ("sizeToFit")]
	public virtual void SizeToFit ()
	{
		Messaging.void_objc_msgSend (this.Handle, selSizeToFit);
	}

Now that’s something the linker can find out since it must analyze the application’s code. Furthermore it also knows, since runtime code generation is impossible on iOS, that the application cannot be extended, unless it’s re-compiled (and re-linked). That’s turning a disadvantage into an advantage! and, starting with MonoTouch 5.3.3, the linker gives you this (small) consolation 😉

This optimization saves 22 kb on a release build of TweetStation but, like most other linker-bindings changes, the real goal was not to save space (it’s still nice) but to reduce the number of conditions and branching in the code to allow faster execution.

Advertisements

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.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s