Tuesday, March 31, 2015

The Linker - Mono's virtual 400 HP code chainsaw

One behind the scenes tool that most Xamarin newbies don't know nothing about is the linker. The linker gets called during the build of your assemblies. It has a single purpose and that is to reduce the size of your assembly. So how does it do that you say! It does it by firing up a digital, virtual, 400-HP chainsaw and cuts away the parts that your code doesn't use.

GREAT! How do I enable it?!

For iOS and Android the linker is enabled by default for projects that targets actual devices and disabled if you target emulators/simulators. The reason for this is to reduce build time when deploying to a simulator.

You can edit the linker settings under project properties; iOS build for iOS and Android options for Android. 

Anything else I should know

Yes, there are three levels of linking;
  • Link all assemblies which means that all code is subject for linking
  • Link SDK assemblies only which means that only Xamarin Core assemblies will be linked. Default for deploy to actual devices.
  • Dont link which means, well, don't link... Default for deploy to simulators/emulators.

Outstanding, why don't I use Link all all the time then!?

The first reason is that deploy time increases since linking takes time. So when deploying to the simulator or for your device while testing, it simply is not worth the extra time.

The other more important reason that should've been first is that the linker can be slightly evil. It can remove stuff that you meant to keep. Linking is carried out through static analysis of the code, so any classes that are instantiated through reflection and sometimes through IoC will not be detected and so they will be cut away. You can save the day by using the [Preserve] attribute to decorate classes and tell them to hide from the linker. If you're coding in a PCL that doesn't have the PreserveAttribute references you can just roll your own. Simply call it "PreserveAttribute" and the linker will see it. Think of it as garlic for linker vampires...

The third reason not to use link all is that this might affect any third party libraries that you have referenced that isn't "linker friendly".

So what's the summary of all this

Simply leave the linker as is and carry on with your life. Nothing to see here, circulate!


No comments:

Post a Comment