Memory Optimization in Android development

Source: Internet
Author: User
Tags arrays constant final garbage collection stringbuffer

One, Android application memory optimization

In the process of developing Android apps, there are often memory pressures, such as oom, or frequent GC. This article is not intended to cover all aspects of memory optimization, just to introduce myself to the problems and solutions I have encountered.

1. Identify code paths that frequently allocate memory

In general, paths that frequently allocate memory may be the method of drawing (draw) related, typographic (layout) related methods, and some callback methods (especially the sensor callback method). You might check this part of the code and then optimize it. However, memory allocations can occur more under the call chain, and it is difficult to check the code. Here a tool is recommended, DDMS under the allocation Tracker. It can show the part of the program running frequently allocating memory, and accurately locate the corresponding code.

2. Reduce the frequency of memory allocation

While Java is automatically recycled memory, frequent memory allocations will definitely increase the pressure on the GC, causing the program to run smoothly. Reducing the frequency of creating objects or not creating them in these places is an obvious way to do this. However, there are some more hidden memory consumption points, the following describes the memory consumption of the For loop.

We know that in Java, for loops are written in two ways:

    ArrayList ();


for (int i  ; I  size (); i) {
       s get  (i);
      
}


for (s:) {
      
}

The second is the Java recommended method, but it needs to allocate an iterator object. If you are in a method such as OnDraw, you need to allocate a small chunk of memory each time you call. So, I recommend using method one in a method such as OnDraw.

Two

With the development of technology, smart phone hardware configuration is more and more high, but it compared with the current PC, its computing power, endurance, storage space, etc. are still subject to a great limit, while users of the mobile phone experience requirements far higher than the desktop applications pc. The above reasons are enough to require the developer to concentrate on implementing and optimizing your code. Choosing the right algorithm and data structure is always the first thing that developers should consider. At the same time, we should always remember to write the two basic principles of Efficient Code: (1) do not do unnecessary things; (2) Do not allocate unnecessary memory.

I've been working on Android since last year, combining my own little project experience, taking into account Google's optimized documentation and many of the technologies on the web, to sort out this document.

1. Memory optimization

The Android system limits the amount of RAM that can be used per software (e.g., Nexus one's memory limit for each software is 24M), while the Java language itself consumes memory, and the Dalvik virtual machine consumes a certain amount of memory, so it's reasonable to use memory, Highlight the qualities and skills of a programmer.

1) Understanding of JIT

Just-in-time compilation (Just-in-time Compilation,jit), also known as dynamic translation, is a technique that improves bytecode compilation language performance by translating bytecode into machine code at run time. The two run-time theories of Just-in-time compilation are bytecode compilation and dynamic compilation. Android Original Dalvik virtual machine is implemented as an interpreter, the new version (android2.2+) will be replaced by the JIT compiler implementation. Performance tests show that the new version is about 6 times times higher than the previous version in multiple tests.

For details please refer to: http://hi.baidu.com/cool_parkour/blog/item/2802b01586e22cd8a6ef3f6b.html

2 Avoid creating unnecessary objects

Like there is no free lunch in the world, there is no free object in the world. Although GC creates a temporary object pool for each thread, the cost of creating objects becomes smaller, but allocating memory is never more costly than allocating memory. If you allocate object memory in the user interface loop, it triggers periodic garbage collection, and the user feels like a hiccup. So, unless necessary, try to avoid examples of objects. The following example will help you understand this principle: when you intercept a string from a user's input, try to use the SUBSTRING function to get a substring of the original data instead of creating a separate copy for the substring. So you have a new string object that shares a char array with the original data. If you have a function that returns a string object and you know for sure that the string will be appended to a stringbuffer, change the parameter and implementation of the function and attach the result directly to the stringbuffer instead of creating a short-lived temporary object.

A more extreme example is the partitioning of multidimensional arrays into multiple one-dimensional arrays:

An int array is better than an integer array, which also sums up a basic fact that two parallel arrays of int are much better than the (Int,int) object array performance. In the same vein, this test is used for all basic types of combinations. If you want to use a container storage (foo,bar) tuple, try using two separate foo[] arrays and bar[] arrays, which are more efficient than (foo,bar) arrays. (There are exceptions, too, when you create an API to let someone call it.) At this point you should pay attention to the design of API interface and sacrifice a little speed. Of course, within the API, you still have to be as efficient as possible.

In general, avoid creating short-lived temporary objects. Reducing the creation of objects reduces garbage collection and thus reduces the impact on the user experience.

3 static method instead of virtual method

If you do not need to access the fields of an object, set the method to static, and the call accelerates 15% to 20%. This is also a good practice because you can see from the method declaration that calling the method does not need to update the state of the object.

4) Avoid internal getters/setters

In the source language like C + +, it is common practice to use getters (I=getcount ()) Instead of direct field access (I=mcount). This is a good habit in C + + because the compiler will inline these accesses, and you can add code at any time if you need to constrain or debug access to those domains. And in Android, that's not a good idea. Virtual method calls are much more expensive than direct field access. It is often reasonable to use getters and setters in public interfaces based on object-oriented language practice, but direct access is preferable in classes where a field is frequently accessed. Without JIT, direct field access is approximately 3 times times faster than the invocation getter access. When JIT is available (the Direct Access field cost equals local variable access), it is 7 times times faster.

5 Cache member to local

Accessing a member variable is much slower than accessing a local variable, and the following code:

(i =; I <.mCount; i++)  {
Dumpitem (. mitems);
}
It is better to change this way:
  =. Mcount;
item[] items =. Mitems;
(i =; i < i++)  {
       dumpitems (items);
}

Another similar principle is: Never call any method in the second condition of for. As shown in the following method, the GetCount () method is invoked at each loop, which is much more expensive than saving the results in an int first.

Also, if you want to access a variable multiple times, it's best to create a local variable for it, for example:

  (Canvas Canvas,  width,  height) {
   (ishorizontalscrollbarenabled ()) {
      intsize = Mscrollbar.getsize ();
        (Size <=) {
          size = mscrollbarsize;
         }
    Mscrollbar.setbounds (, height-size, width, height);
    Mscrollbar.setparams (Computehorizontalscrollrange (), Computehorizontalscrolloffset (), Computehorizontalscrollextent (),);
    Mscrollbar.draw (canvas);
   }

There are 4 accesses to the member variable Mscrollbar, and if you cache it locally, 4 member variable accesses will become 4 more efficient stack variable accesses.

The other is that the parameter of the method is the same as that of the local variable.

6 Use the static final modifier on constants

Let's take a look at the declarations in front of the class for these two paragraphs:

static int intval = 42;

static String Strval = "Hello, world!"

It will generate a method called Clinit initialization class, which is executed when the class is first used. Method assigns 42 to Intval, and then assigns a reference to the constant table in the class to Strval. When these values are to be used later, they are found in the table of member variables. Now let's make some improvements and use the final keyword:

static final int intval = 42;

Static final String Strval = "Hello, world!";

Now, the class no longer needs the Clinit method, because constants are saved directly to the class file when the member variable is initialized. Code that uses intval is replaced directly with 42, while using strval points to a string constant instead of using a member variable. Declaring a method or class as final will not improve performance, but will help the compiler optimize the code. For example, if the compiler knew that a getter method would not be overloaded, the compiler would invoke it inline.

You can also declare a local variable final, and again, this will not result in a performance boost. Using final only makes local variables look clearer (but sometimes this is necessary, for example, when using anonymous inner classes).

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.