Optimization techniques in Java (for Android)

Source: Internet
Author: User
Tags finally block stack trace

The recent machine memory is full, in addition to new machine memory, but also should be a good review of our code, a lot of code to write too casually, these bad habits or the language of the program is not understood to be a good suppression of repression.

Here are some of the things you can do in Java programming as a summary of the reference network resources.

  1. try to use a single case in the appropriate situation

Using a single example can reduce the load burden, shorten the loading time, improve the efficiency of loading, but not all places are applicable to a single case, simply speaking, the single case is mainly applicable to the following three aspects:

1 control the use of resources, through thread synchronization to control the concurrent access of resources;

2 control of the production of instances in order to achieve the purpose of saving resources;

3 control data sharing to enable communication between multiple unrelated processes or threads without establishing a direct association.

  2. try to avoid using static variables arbitrarily

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

public class a{

Static b b = new B ();

}

At this point, the lifetime of static variable B is synchronized with Class A, and if Class A does not unload, the B object will reside in memory until the program terminates.

  3. try to avoid too often creating Java Objects

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.

  4. Use the final modifier as much as possible

A class with a final modifier is not derived.

In the Java Core API, there are many examples of final applications, such as java.lang.String. Specifying final for the string class prevents the consumer from overwriting the length () method.

In addition, if a class is final, all methods of that class are final. The Java compiler looks for the opportunity Inline (inline) for all final methods (this is related to the specific compiler implementation). This will increase the performance by an average of 50%.

  5. use local variables as much as possible

The parameters passed when the method is called and the temporary variables created in the call are saved in the stack, which is faster.

Other variables, such as static variables, instance variables, and so on, are created in the heap and are slower.

  6. try to handle the use of both the packing type and the basic type

Although wrapper types and basic types can be converted to each other during use, they produce a completely different area of memory, with basic type data generation and processing in the stack, the wrapper type being the object, and the instance being generated in the heap.

In the collection class object, there are objects that require processing for the wrapper type, and other processing advocates the use of basic types.

  7. use synchronizedcarefullyto minimize the synchronize method

All know that the implementation of synchronization is a great cost of overhead, and may even lead to deadlock, so try to avoid unnecessary synchronization control.

When the Synchronize method is called, it locks the current object directly, and other threads cannot invoke the other methods of the current object until the method finishes executing.

So the method of synchronize is as small as possible, and should try to use method synchronization instead of code block synchronization.

  8. use StringBuilder and stringbuffer for string connections whenever possible

That's not much to say.

  9. Try not to use the Finalize method

In fact, it is very bad choice to put the resource cleanup in the Finalize method, because the GC workload is very large, especially when recovering Young's memory, most of which will cause the application to pause, so the choice of using the Finalize method for resource cleanup will lead to greater GC burden, Programs run less efficiently.

   Try to use basic data types instead of objects

1

String str = "Hello";

In this way, a "hello" string is created, and the character cache pool of the JVM also caches the string;

1

String str =newstring ("Hello");

At this point, in addition to creating a string, str refers to the bottom of the string object also contains a char array, this char array is stored in sequence H,e,l,l,o

   Single thread should try to use HashMap,ArrayList

HashTable, vectors, etc. use the synchronization mechanism to reduce the performance.

   Create HashMap as reasonable as possible .

When you want to create a larger HashMap, take advantage of another constructor public HashMap (int initialcapacity, float loadfactor) to avoid HashMap multiple hash refactoring, Expansion is a very expensive thing, in the default initialcapacity only 16, and Loadfactor is 0.75, how much capacity, you'd better be able to accurately estimate the best size you need, the same hashtable,vectors is the same truth.

   minimizing The repetition of variables

Such as

1

For (Inti=0;i<list.size (); i++)

should read

1

For (Inti=0,len=list.size (); i<len;i++)

And in the loop should avoid the use of complex expressions, in the loop, the loop condition will be repeated calculation, if you do not use complex expressions, and the loop condition value is not changed, the program will run faster.

   try to avoid unnecessary creation .

Such as

1

2

a =newa ();

if (i==1) {list.add (a);}

should be changed to

1

2

3

if (i==1) {

a =newa ();

List.add (a);}

   Release Resources in the finally block as much as possible

The resources used in the program should be freed to avoid resource leaks.

This is best done in the finally block. The finally block is always executed, regardless of the result of the program execution, to ensure that the resource is closed correctly.

   try to use shift instead of 'A/b' operation

"/" is a costly operation that uses shifting operations to be faster and more efficient

Such as

1

2

Intnum = A/4;

Intnum = A/8;

should be changed to

1

2

Intnum = a >>2;

Intnum = a >>3;

Note, however, that the shift should be annotated because the shift operation is not intuitive and more difficult to understand

   try to use shift instead of 'a*b' operation .

Similarly, for the ' * ' operation, using the shift operation will be faster and more efficient

Such as

1

2

Intnum = A;

Intnum = a *8;

should read

1

2

Intnum = a <<2;

Intnum = a <<3;

   try to determine the capacity of the stringbuffer .

The StringBuffer constructor creates an array of characters with a default size (usually 16). In use, if this size is exceeded, the memory is redistributed, a larger array is created, the original array is copied, and the old array is discarded.

In most cases, you can specify the size when creating the StringBuffer, which avoids auto-growth when the capacity is insufficient to improve performance.

Such as:

1

StringBuffer buffer =newstringbuffer (1000);

   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.

For example:

1

2

3

4

5

Publicvoidtest () {

Object obj =newobject ();

......

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:

1

2

3

4

5

6

7

Publicvoidtest () {

Object obj =newobject ();

......

Obj=null;

Execute time-consuming, memory-intensive operations, or call time-consuming, memory-intensive methods

......

}

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 avoid using a two-dimensional array

Two-dimensional data occupy more memory space than one-dimensional array, about 10 times times more.

   try to avoid using split

Unless it is necessary to avoid using split,split because it supports regular expressions, it is less efficient, and if it is frequent dozens of, millions of of calls will be resource intensive, and if you do need to call split frequently, Consider using Apache's Stringutils.split (String,char), which can cache results with frequent split.

  ArrayList & LinkedList

One is a linear table, one is a list, a sentence, random query as far as possible to use arraylist,arraylist better than linkedlist,linkedlist also move the pointer, add the deletion of the operation LinkedList better than ArrayList, ArrayList also want to move the data, but this is a theoretical analysis, it is not necessarily the case, it is important to understand the 2 data structure, the right remedy.

   try to use system.arraycopy () instead of iterating through the array .

System.arraycopy () is much faster than copying an array by looping

   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.

   Caution with exceptions

When creating an exception, you need to collect a stack track, a stack trace that describes where the exception was created. Building these stack traces requires a snapshot of the runtime stack, which is a very expensive part.

When you need to create a Exception, the JVM has to say: Don't move, I want to save a snapshot of what you are now, so stop the stack and the stack operation temporarily. Stack traces contain not only one or two elements in the runtime stack, but each element in the stack.

If you create a Exception, you have to pay the price. Fortunately, the overhead of catching exceptions is small, so you can use Try-catch to wrap the core content together. Technically, you can even throw an exception at random without a big cost. It is not a throw operation that incurs a performance penalty-although it is somewhat unusual to throw an exception without pre-creating an exception. The real cost is to create the exception.

Fortunately, good programming habits have taught us that you should not throw an exception 3,721 or so.

Exceptions are designed for exceptional situations and should be kept in mind when used.

Android Optimization Tips:

1, the amount of data hit when possible to use lazy page loading

2, frequently used data is best to cache, to avoid multiple loading

3, frequently used pictures, try to load the first time to get the cache to local, next read local can

4, ListView, GridView, etc. must be optimized to use

5, bitmap picture if too large, try to compress after use, after use, use recycle to release

6. Open threads as little as possible, such as new Thread (). Start (), try to use thread pooling to manage threads uniformly, avoid creating redundant thread objects, and not reuse

7. Database result set cursor must be closed after use

8, network image loading, the best use of thread pool and LRU algorithm implementation

Optimization techniques in Java (for Android)

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.