Your App, but Better
This guest post was written by Tomáš Slavíček, a developer from Prague, Europe. You can learn more about him on Twitter or view additional watch faces byTomáš on the Connect IQ Store.
So how can we save some memory? We have a lot of options. We can rewrite the code and keep only the most needed parts. If there is a similar logic located in multiple places, we can move it into one function, which will read a parameter.
We should also check if we really need to include all the resources, images and fonts in the project.
By using specific folder names, we can specify which images or files should be included on each platform. We can distinguish devices by their specific name, display resolution or the roundness of the display:
We can even exclude specific code files based on the device. For example, on fēnix 3 we don’t need to include the logic for downloading data from the internet, because fēnix 3 does not support background tasks. Also, devices without a heart rate sensor do not need to have this functionality in the code.
A more modern and better alternative to build excludes are jungle files. We are not specifying what needs to be excluded instead of what will be included. They have a bit more complicated structure and lots of parameters and options. You can read more about jungle files here.
Other memory optimizations
We can also save more memory with these few tips:
- Do not use built-in XML layouts for your application, instead draw every text and image manually in the onUpdate by dc.draw() calls. You can find a tutorial here.
- Be aware that string, long and double types are complex objects and take more memory, also the enums and constants are objects. Use just float or number types.
- And when you don’t need an object anymore, just set this variable to null. Reference counting in Monkey C is very simple and this will help to free up the memory.
- Beware of arrays of arrays. If you want to save the list of X and Y values, it’s better to save them as two separate arrays [x1, x2, x3] and [y1, y2, y3], instead of [[x1, y1], [x2, y2], [x3, y3]].
- Switch/case blocks can also take more memory than if/else, but who cares? 🙂 You don’t need to optimize everything.
Objects in the memory
Another important parameter is the number of objects used in the application. We can use about 65535 objects on fēnix 5, but this number is much lower for fēnix 3, just 512 objects. We can also see this value in the File→ View Memory window in the simulator.
String, long and double types are counted into this limit, also all instances of custom classes, enums, constants, dictionaries, and other objects. Float or number types are fine, these are just simple types.