Google developing for Android two-Memory Best Practices | Classification in Android Best practices
Original: Developing for Android, II
The Rules:memory
In determining the behavior of the application, whether there is a good user experience and the overall device experience, the use of memory may be the most important of the independent factors. Memory factors include the memory footprint of the application and the memory churn (resulting in a garbage collection that has an impact on performance during the run).
Avoid allocating memory in loops
Memory allocation is unavoidable, but should be avoided as much as possible, especially in trivial calls to blocks of code. In the drawing code, for example, the method will be executed for each frame of rendering.
Avoid allocating memory in the OnDraw method of the custom view, because the animation might call it. Replacing a temporary object with a cached object avoids the new memory overhead. A typical example is the assignment of a new paint object in the OnDraw method, because the canvas requires a paint object. For instances of this custom view, only a separate paint object is assigned and then temporarily used in the OnDraw method is better.
Avoid memory allocations where possible
Avoid constant, temporary variable memory allocations. Some of the following strategies may not be appropriate for traditional Java coding, but are recommended for Android development. Tools can often be used to help us decide whether a piece of code needs to be optimized. A more concise and traditional abstraction layer is a good choice if some part of the code is rarely executed (for example, if the user changes some of the settings). But if the analysis shows that some code executes frequently and causes a lot of memory churn, consider the following strategy:
-
Object Cache
Reusing objects is useful in the redistribution of some constant memory, such as avoiding memory allocations in internal loops. For example, some frequently called methods may require a Rect object to store some intermediate values, preferably a rect as a class-level constant, allocating only one memory at a time, or even static, to avoid assigning each method call. Some of the caveats about the singleton are also applicable to this approach, and on Android, the common flaw with static is that they are static for a process, but there may be multiple activities in the same process. Careful application, this technique is common in avoiding memory redistribution
-
Object Pool
If the code temporarily requires multiple objects of the same type, consider applying the object pool rather than allocating memory frequently. But object pooling may not be easy to manage. If the object is stateful and is accessed by any thread, be aware of some concurrency issues. There are also problems with memory pressure (you can use the LRUCache policy), and the increase in objects has the risk of memory leaks, so when you use object pooling, consider using it only in specific situations. If this strategy is useful on low-or low-memory configurations or devices, you should use the API version or the Islowramdevice () method to detect object pool usage restrictions
-
Arrays
ArrayList is a convenient collection and does not cause too much allocation. It will be redistributed, and the current array will be copied back to the list, but setting a reasonable initialization capacity avoids the frequent allocation of memory. If your collection does not require a dynamic change size, consider using array
-
Andorid Collection Class
Unless you need a map to store large amounts of data, consider using Arraymap or SIMPLEARAYMAP as a data structure rather than a hashmap. These classes are optimized to have higher memory efficiency and less GC pressure relative to HashMap, and such data structures can better meet common usage scenarios on mobile devices (and they also support entity traversal without using iterator). Of course, consider setting an appropriate initial capacity to avoid auto-scaling
-
Ways to modify an object
In this case you should not return a new object, consider passing the object as a parameter to modify the object:
|
Rect getrect (int w, int h) |
- Avoiding the use of integer,float instead of Int,float when the original type can be met causes memory allocations, automatic boxing, and more allocations of the object's own memory. For example, if you have an integer in your method and then the code call comes with an int, the automatic boxing will result in a memory allocation. collection classes and generics with traditional types may be unavoidable, but the wrapper type should be avoided when the original type can be done. Some collection classes like Sparseintarray and Sparselongarray are available in Android, and they are used internally as primitive types rather than object types.
- avoid an array of objects if you have a simple set of data objects, consider storing each field in an array. For example, suppose you need to track some of the previous touch x/y point data as you draw. You should use two int[] to save them, one for storing x-coordinate values and the other for storing y-coordinate values instead of using a point[]. This not only reduces the number of original objects (saving memory), but also increases the locality of the data, can better utilize the valuable memory and CPU cache.
Avoid interators
Explicit ( List.iterator() ) or ambiguous ( for(Object o : myObjects) ) use of interator will result in the memory allocation of a Interator object. A single memory allocation is not a big deal, but you should try to avoid allocating memory in the internal loop. Of course, the direct use of the corner tag for collection traversal can be done without allocating any memory.
|
Final count = myList. (); (i =; i < count; ++i) { Object o = mylist.get (i);
|
It is important to note that Interator always results in the allocation of a memory, even if it is an empty collection. Therefore, if you want to use foreach, you should be able to perform a isempty test before traversing the collection.
Enumerations can often be used to represent constants, but are more expensive than the original type, which involves the size of the code and the allocation of the enumeration object's memory.
A temporary enumeration does not result in large memory consumption. But Proguard will, in some cases, perform some static parsing of all the code, optimizing the enumeration to an int value. When enumerations are widely used throughout the application, or when an enumeration in a library or an API is used by many other applications, it is a problem, even worse.
Using annotations in the AndioStudio1.3 version @IntDef will ensure that your code is type-safe during the build period (when lint error is turned on). Therefore, using the INT variable is better for both performance and code volume.
Avoid frameworks and libraries for non-mobile applications
Some of the familiar Java platform frameworks, such as annotation-dependent guice, are sometimes used. But it is not optimized for mobile apps, and using them will cause some problems.
If you just use a small part of a library, you can try to extract that part. Even if Proguard can skip those unused code in many cases, a dependency graph in a large library can cause optimizations to fail (and greatly increase the build time of Proguard).
Some libraries are introduced into Android apps, but you should not use them, unless you are familiar with it and know the problems it may bring to your application.
Another problem is that using those non-moving frames and libraries can increase the overhead of memory. You can detect how much problem they cause by monitoring the use of memory and the behavior of the garbage collector.
Avoid a static memory leak
It is useful to avoid using static objects for temporary memory allocations. However, it should be noted that when using static variables to cache objects, they should not actually persist throughout the lifetime of the process. In particular, these static variables should not be consistent with the life cycle of the activity. For example, the activity will destroy and recreate when the screen orientation changes, but the static variable holds a reference to the activity, which can cause a memory leak. Activities are very resource-intensive, and this memory leak can quickly cause your application and system to oom.
Avoid finalizers
Because of the differences with the Java language seats, finalizers needs not a garbage collector, but two. This means not only that the resources will be frozen until the two garbage collector is triggered, but also that running two garbage collector at the same time in the system can lead to resource consumption and finalizer. There is a special case that needs to be finalization when your object holds a local pointer. If this is not the case, you can completely avoid finalizers.
If you do need finalizers, consider implementing the Autocloseable interface and releasing all resources within your code domain through the Close method.
Avoid excessive static initialization
During some important time in your application (such as when booting up), too much initialization can lead to performance problems and poor user experience. You can load the code when you need it.
Releasing the cache with commands
The Ontrimmemory () callback method provided from API 14,COMPONENTCALLBACKS2 allows your app to free memory in the case of low memory pressure. For more details, please refer to the Google I/O 2012 video Doing More and less, showing an example of how to LRUCache handle bitmap.
Using Islowramdevice ()
Activitymanager.islowramdevice () that appears in the KitKat version Method can help you detect memory limits when your app is running. When you have some features in your application that are better than memory, you can detect whether memory is satisfying your features, and then decide whether to turn it on.
Avoid requests for larger heap memory
Apps can turn on the ability to request larger heap memory by setting the application tag in the Mainfest file, but you shouldn't. The behavior of requesting a large heap may be that the application considers only its own needs, but it is an error decision for the entire device-level experience.
Requesting a large heap may be necessary in rare cases, such as the processing of media content. However, the application uses this feature only to better manage memory and resources rather than to cause the user experience of the entire device to become worse. Applying a larger heap will cause other processes on the device to have less memory, and when the user switches activity it can cause other apps to be killed and restarted.
Avoid running the service too long, if necessary
Each process has a resource limit in the system. If you don't need the service to run consistently in the background, turn it off in a timely manner.
Android provides a number of mechanisms to ensure that components run only within a specific scope:
- Use Broadcastreceiver to receive events that are important but infrequent, rather than using a service that is useless for most of the time, such as network state changes or alarm. The app can turn off broadcastreceivers when it is not needed, so that the system is awakened only when it is needed.
- Use Intentservice to implement a service that automatically shuts down when the task stack is empty
Optimize code size
Thin apps will run faster. The less code you load, the less time users will have to download your app, and your app will start and initialize faster. Here are some suggestions:
- Use Proguard to remove useless code. You can also use Gradle, and it will remove useless code from the libraries you rely on.
- Be cautious when you just need a certain type of data, don't use a library that has a large collection of different collections.
- Make sure you understand the consumption of those automated generated code
- The simpler the better, the more directly solve the problem, rather than create a lot of structure and abstraction to solve the problem
Google developing for Android two-Memory best practices//Lightsky ' Blog