Search code examples
javaiphoneandroidmemorysmartphone

Generally speaking, do I write code that saves memory or code to save processing time for simple objects for smartphone applications?


I’m not sure this is the best example, but here goes. Let’s say I want to draw an object to a canvas in an Android application. I need to do some math and call a method to return screen size to figure out where to draw it since my app should support multiple screens. I really only need to do this procedure once, as every time I want the object to be drawn, it is drawn to the same place. If I only do the procedure once, I have to hold the return values in memory so I can refer back to them later.

Alternatively, I could call the procedure to get these values every time I want to draw the object, so I don’t have to hold any values in memory for the entire lifetime of the activity.

Now I know, not all cases will be the same because I could write a fancy 100,000 line algorithm that just returned an integer value, or go to the opposite extreme, but I’m hoping that there is a common knowledge tradeoff that is generally considered acceptable.

So, what is the correct approach? Can you elaborate?

Thanks folks!


Solution

  • The common knowledge tradeoff I use is, "Do not prematurely optimize." I build my code, choosing the simplest, clearest implementation I can make at the time. This is the fastest way to write correctly working code. Then I test and profile the code. Only then do I address the areas that need optimization.

    If the profiled code uses too much memory, I go back and optimize for space verses time. Or vice versa if the profiled code runs too slowly.

    If I spend too much time pre thinking about how to optimize the code I introduce unnecessary complications and invariably fail to give proper attention to the important optimizations in the final system.