Basics of Computational Coding Practices for iOS Apps
Less computation in your coding practices will improve your iOS app’s performance. Here are some actions you can take so as to improve the overall performance of your programming:
Save intermediate results in variables and then reuse them, especially in loops. Here’s a simple example of this technique, taken from the androidTakesATurn method in the TTTGameSessionViewController class:
… // Play at that square pickedX = [picked x]; pickedY = [picked y]; [activeGame play:pickedX :pickedY]; [gameView placeSymbol:pickedX :pickedY]; …
Avoid internal getters and setters. Access member variables directly when within the class, instead of using the getters and setters. Doing so avoids the overhead of an additional method call.
You can see this process in the GameGrid class, where the locations in the two-dimensional array member variable grid are accessed directly instead of using the accessor methods setValueAtLocation(…) and getValueAtLocation(…), which is how the grid is accessed outside the class by client classes such as Board and Game.
Avoid creating unnecessary objects. Instances of the Objective-C NSString class (though appearing to be elementary data types) are objects, so limit their number as well. This tactic is illustrated in the Symbol class in Tic-Tac-Toe, where you use the Singleton pattern so that only one instance of an X, an O, and a Blank symbol is ever created; also, symbols are defined as enumerated types rather than as strings.
Know the framework libraries well, and use them wherever possible instead of writing your own code. Because the library-implemented code is optimized (for example, by using assembler code), using it is more efficient than writing equivalent code, even after the compiler tries to optimize it.
An excellent set of old-but-gold techniques around low-level coding practices for efficiency is Jon Bentley’s rules for writing efficient programs. You can find summaries of these techniques at various places on the web by entering Jon Bentley writing efficient programs in your favorite search engine.