Android Optimizer-related to Java-memory

Source: Internet
Author: User


Memory optimized

The Android system limits the amount of RAM that each software can use (for example, the Nexus one has a memory limit of 24M per software), while the Java language itself consumes memory, and the Dalvik virtual machine takes up a bit of memory space. So the rational use of memory, highlighting the quality and skills of a programmer.

1) Learn about JIT

Instant compilation (Just-in-time Compilation,jit), also known as dynamic translation, is a way of translating bytecode into machine code at run time, Techniques to improve the performance of bytecode compilation languages . The two runtime theories of immediate 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 old version in several tests.

Avoid creating unnecessary objects

Just like there is no free lunch in the world, there is no free object in the world. Although the GC has set up a temporary object pool for each thread, you can make it less expensive to create objects, but allocating memory foreveris much more expensive than allocating memory. If you allocate object memory in the user interface loop, it will cause periodic garbage collection, and the user will feel like a hiccup in the interface. So, unless necessary, doTry to avoid an instance of the object. The following example will help you understand this rule:< Span data-mce-= "" > when you intercept a string of data from user input, try to use the SUBSTRING function to get a substring of the original data. Instead of creating a copy for the substring in addition. So you have a   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 exactly that this string will be appended to a stringbuffer, then, change the function's parameters and implementation,   attaches 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 summarizes the basic fact that two parallel int array ratio (int,int)Object array performance is much betterIn the same vein, this test is used for all basic types of combinations. If you want to use a container store ( Foo,bar) tuples; foo[] array and bar[] array, a certain ratio ( Foo,bar) array is more efficient . (The exception to the is when you create an API to let others call it.) At this point you need to note that

Overall, it is to avoid creating short-lived temporary objects. Reducing the creation of objects reduces garbage collection, which in turn reduces the impact on the user experience.

try to avoid the frequently called methods, loops in the new object, because the system not only takes time to create objects, but also takes time to garbage collection and processing of these objects, in the scope of our control to maximize the reuse of objects, it is best to use basic data types or arrays to replace the object .

Overall, it is to avoid creating short-lived temporary objects. Reducing the creation of objects reduces garbage collection, which in turn reduces the impact on the user experience.

Reduce unnecessary global variables

Try to avoid static member variables referencing resources that are consuming too many instances, such as context. Android provides a very robust messaging mechanism (Intent) and task Model (Handler) that can prevent some unnecessary global variables by passing or in the way of events.

Don't rely too much on GC

The Java GC uses a forward graph to determine whether an object is effectively looking at the vertices of other objects that can reach the object, and the overhead of a graph relative to a linked list or binary tree is conceivable. So don't count on the GC too much. The unused object can point it to null and pay attention to the quality of the code. At the same time, the display allows the system GC to recycle, when the case is processed,

if (bitmap.isrecycled () ==false) {//If no recycle     bitmap.recycle ();}

Try to avoid random use of static variables

It is important to know that when an object is defined as referenced by the STATAIC variable, the GC does not normally reclaim the memory that the object occupies, as

Class a{    new B ();}  

Cache a member to a local

accessing member variables is much slower than accessing local variables , the following snippet:

for (int i =0; I <this.mCount; i++)  {dumpitem (this.mitems);}

It's better to change to this:

int count = this.mcount;item[] items = this.mitems;for (int i =0; i < count; i++)  {       dumpitems (items);}

Another similar principle is that you should never call any method in the second condition of a for. As shown in the following method, the GetCount () method is called at each loop, so it is much more expensive to save the results first than you would in an int.

for (int i =0; i < This.getcount (); i++) {Dumpitems (This.getitem (i));}

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

Protectedvoid Drawhorizontalscrollbar (Canvas canvas,int width,int height) {if (ishorizontalscrollbarenabled ()) {intsize =   Mscrollbar . GetSize ( Span style= "color: #0000ff;" >false); if (Size <=0 Mscrollbarsize;}  mscrollbar.setbounds (0, height- Mscrollbar.setparams (Computehorizontalscrollrange (), Computehorizontalscrolloffset (), Computehorizontalscrollextent (), false);  Mscrollbar.draw (Canvas),}}             

There are 4 accesses to the member variable Mscrollbar, and if it is cached locally, 4 access to the member variable becomes 4 more efficient access to the stack variable .

If Mscrollbar is just a basic data type, direct access is acceptable, but if Mscrollbar is a complex object, it is better to copy it, because if you access it,

The other is that the parameters of the method are the same as the local variables.

Release references to useless objects as early as possible

Most of the time, the object referenced by the method local reference variable becomes garbage as the method ends, so most of the time the program does not have to explicitly set the local, reference variable to NULL.

void Test () {    new Object ();    ... obj=null;}    

The above is not necessary, and as the execution of the method test () is completed, the scope of the OBJ reference variable in the program ends. But if it's changed to the following:

void Test () {    new Object ();    ... obj=null// execution time consuming memory operation, or call time consuming memory method ... }      

At this point it is necessary to assign the OBJ value to null to release the reference to the object as soon as possible.

Try to cache frequently used objects

As much as possible to cache objects that are used frequently, you can use arrays, or hashmap containers for caching, but this can cause the system to consume too much cache and degrade performance, and it is recommended to use some third-party open source tools such as Ehcache,oscache for caching. They basically implement a cache algorithm such as Fifo/flu.

Try to avoid very large memory allocations

Sometimes the problem is not caused by the heap state at the time, but by the failure of the allocation. The allocated memory blocks must be contiguous, and as the heap becomes more and more full, it becomes increasingly difficult to find larger contiguous blocks.

Cache

Moderate use of the cache, do not overuse, because the memory is limited, you can save the path address do not store image data, not often used as far as possible not to cache, empty when not.

Android Optimizer-related to Java-memory

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.