Performance optimization---code in android development

Source: Internet
Author: User

Ago

This article mainly summarizes some of the techniques to optimize the code, some of the code to write small details, may affect the execution efficiency of the program, such as a place will only affect the 1ms, then 1000 places will affect 1s,1s in the end is not long? You know, the time for the activity to have a ANR anomaly is 5s!!!
Mainly follow two principles
1. Do not create objects that you do not need to create and define a variable repeatedly
Object creation is a tedious step in which the JVM first parses a symbol through a new directive to determine whether the class is loaded, then allocates memory in the heap, allocates memory space for the object, and then initializes the memory area (0 of 0, which is null, This is why the variables in the method need to be initialized by the programmer, and finally the JVM invokes the object's constructor, and generally there is a variable that establishes a reference to the object.
So, creating objects is a hassle, so don't just create objects with nothing to do.

2. Use the finished object in time to recover
is often said GC, here to be clear, when the GC operation is not determined by the programmer, the JVM will start the GC when necessary, the programmer can only recommend that the JVM as soon as possible to GC for an object, it has two criteria
(1) If the object loses its reference, the best way is to assign null to the unused object
(2) The object leaves the scope, such as the execution of the method, local variables and objects will be recycled, so as little as possible the life of global variables.
And the GC operation is also to consume memory @[email protected]!
  

Start 1. Most frequent + and + "" operations

The + sign in Java can be both numeric and string, but it's a very inefficient way to do string manipulation, although it's very handy!

1.1 Do not use the + number directly for string stitching

It is really handy to use the "+" operator in development, but the efficiency is very low, because the "+" number inside is actually called the StringBuffer append() method and then converted String to, then it is definitely not directly called fast.
Another is StringBuilder that this class is Java1.5 when it comes out, in terms of efficiency, it and the StringBuffer difference is StringBuilder not thread-safe, multi-threaded operation will have problems, then it is easier to choose,
Used in a single thread, used StringBuilder in multi-threadingStringBuffer

1.2 Do not use + "" directly for string conversions

There are three ways to convert objects into strings, from fast to slow, xxx.toString String.valueOf(xxx) xxx +""
  xxx.toStringis a direct conversion, and the String.valueOf(xxx) bottom is called the toString() method, as +"" for, in 1.1 has been said, it will first convert SringBuffer to, and then call toString() , so the results at a glance

The above two points can be seen in the following code

Through the JAVAP-C instructions, you can see the following content, although the left may not be able to understand, but the right note is easy to understand

2. Details of the use of the loop (for example)

The loop is a very high frequency in the development of an operation, its role is to simplify the repeated steps, such as adding 10,000 pieces of data to a set, if not the loop, even if the copy and paste is a long time, but through the loop operation can be a few lines of code to complete. But in this case, there will be some small details that may affect the execution efficiency of the program. The following code example:

1 New Arraylist<>(); 2  for (int i = 0; i <; i++) {3     New Random (); 4     Integer result = Random.nextint (+); 5     String s = result.tostring (); 6     List.add (s); 7 }    

2.1 Try not to create unnecessary objects in the loop

The sample code creates 100 random objects in the For loop, and the actual random number operation is the object's nextInt() method, which can actually be written as:

  

New Arraylist<>(); // object created outside the For loop New Random ();  for (int i = 0; i < i++) {    = Random.nextint (+);     = result.tostring ();    List.add (s);}

2.2 Unused objects to be recovered in time


Here is just an example, the actual development is likely to occur in the case of parsing a piece of JSON, and then get to an object in the JSON and added to the collection, then the parsed object is actually useless, because the data has been added to the collection, compare we want to use data instead of objects, This can be set to NULL, allowing the JVM to reclaim it as soon as possible, which is a very good habit,

But there are times when, in this case, the object is set to NULL, but the object's reference is still held by the list collection, so the object is not recycled

  

1list<string> list =NewArraylist<>();2Random random =NewRandom ();3 Integer result;4 String S;5  for(inti = 0; I < 100; i++) {6result = Random.nextint (100);7s =result.tostring ();8 List.add (s);9result =NULL; At this point, the object is set to NULL, but its reference is still held by the list, even if result is null, it will still not be recycledTens =NULL; One}

It's a good idea to empty the list collection and set the list to null

1  list.clear (); The object held by the list should be emptied by 2ifnull) {3     null; 4 }

In the actual development, it can be written in the Ondestory () method

2.4 Appropriate methods for establishing the cache of the results

Like sometimes it's written for simplicity.



Java calls a method, in fact, is not so simple, to create a stack frame to store local variable table, operand stack, dynamic connection, method return address, and method call site, restore method call scene and a series of operations. Therefore, if the size of the list () is very large, it also affects efficiency, so you can define a variable instead of directly using the

  

3. Use of IF and switch

Since there is a cycle, then there should be judgment @[email protected]!

3.1 Create an object or invoke a method at the appropriate time by using the IF

This is a small detail.


As you can see in this loop, the data is only added when the random number is 20, so it makes no sense to call the random number method before this toString() . So it can be written as
  

4 using bit arithmetic instead of multiplication operation

The computer only knows the binary, and the bitwise operation is the direct binary operation, so of course the efficiency is higher,

Of course there are shortcomings.
(1) for the number is too large, or direct multiplication more convenient
(2) Code readability is not high

5 Rational use of activity life cycle

The life cycle of activity is most commonly used onCreate() , but other life cycles I think are also necessary to be used properly.


This is only a personal writing habit, do not know whether it will affect performance, but at least this code structure is relatively clear:)

6 using Zipalign for code alignment

Zipalign is a tool under the SDK to align the uncompressed data in the APK file on 4-byte boundaries, and when the resource file is aligned to a 4-byte boundary through memory mapping, the Android system can read the file by calling the Mmap function.
The Mmap function is the calling function of the Linux system, which provides a different way of accessing ordinary files, and the process can operate on ordinary files like reading and writing memory, and the process can operate on ordinary files like read and write memory, without having to read () and write () to obtain higher performance on reading resources. If the resource itself is not aligned, it must read them explicitly-the process will be slow and will cost extra memory.
Specific usage I'll summarize in the tool

7 using Sparsearray instead of HashMapSparseArrayTo replaceHashMap, because of an Android studio prompt,



UseSparseArrayThanHashMapOkay, so I looked it up online.SparseArraySome of the relevant information
In simple terms,SparseArraySuitable forHashMap<Integer, Object>Such a structure, becauseSparseArrayIt's used internally.intType array StoragekeyAndObjectType of array storagevalueOf the value, eliminating theintPackaged intoIntegerThe process.


According to this article, it can be seen that, when there is too much data, the efficiencySparseArrayAnd there is no betterHashMapFaster, but at the end of the article the author says memory usage can save 27%
  

The author of this article specifically tested the use of memory, saying that it was optimized in memory by 35%


I watch memory consumption using the tools that my Android studio comes with.HashMapAbout in3.24~3.31


andSparseArrayAbout in3.0~3.1Between


but the specific optimization of how much is not the focus, anyway, it is SparseArray开销更低 more advantageous to the memory cost!
In addition toSparseArray,ArrayMap, Sparseboolmap,sparseintmap,sparselongmap,longsparsemap and so on some column API, in terms of memory use relative to the hashmap is much better

8 I/O streams try to use buffer-

I/O objects with buffer buffers are more efficient than non-bands,

9. Can not static will not be static, can final final

  staticIt's good for members to use, but it will prolong their life cycle.
  finalThe object cannot be inherited, the variable cannot be modified, the method cannot be overridden, and it is inline

End

Temporarily think of so many, just some of the development of the details, some well-known did not write, such as re ListView -use ConvertView , compressed pictures, asynchronous loading and so on,

Performance optimization---code in android development

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.