By Darryl Mocek on Apr 16, 2013
In this 5th installment of Embedded Development, I'm going to talk about efficiency. Efficiency has to do with, well, being efficient. It has to do with not being wasteful...not doing things which don't need to be done. It also has to do with doing things more efficiently...doing things you wouldn't normally do to have more efficient code.
A good example of this is moving fields to helper classes. If you have a class which contains fields which aren't used often, consider moving them to a helper class which contains sparsely-used fields. You will save memory and CPU cycles when the fields are not used. The memory and CPU will only be incurred when the fields are used. This is something you wouldn't normally do. I'm not talking about fields shared by multiple classes, which you do put into shared classes. This falls under the category of making your Java classes efficient (read smaller, using less memory, and less CPU in the typical case).
Related to moving fields to helper classes is grouping like-used fields together in shared classes. If you put too few fields in too many classes, you'll end up burning CPU and memory instantiating too many fields. Put fields which are likely to be used by the same functionality in shared classes. This is especially useful when the fields are static.
Simply eliminate extra fields. This one should be obvious, but if you've removed a reference to a field, make sure the field is still needed. A good IDE can help with this.
Use smaller buffers. This is related to the cache discussion in 'Part 4 - Tunability'. When using buffers, you should make them small and grow them as needed. Growing your buffers will incur some CPU cycles *when they grow*, but only then. Take care to ensure you don't make them too small and grow them in too small chunks. Testing and profiling will help find the sweet spot.
Use the smallest data type you can for each field. Do you really need a long or will an integer do just as well? Do you really need an integer or will a short do just as well. I rarely see the use of shorts. Most of the time I see ints used.
Keep stack frames small. This is especially important in recursive calls.
Avoid idle tasks which prevent the CPU from sleeping or going into low-power mode.
Usually once you start thinking in terms of efficiency (size/memory, less code/CPU) rather than just functionality and performance, you'll start getting creative ideas for keeping data structures smaller. Don't forget to get creative with your data structure layouts as well!