Android code optimization articles

First, the selection data structure

1、Array、ArrayList、List、LinkedList、HashMap、HashSet、HashTable区别

Array

An array (Array): is a linear table data structure. It uses a set of contiguous memory space to store a set of data having the same type, and does not support dynamic expansion.

Linear table
linear form is arranged in a line as a data structure, each of the linear forward and backward directions most two tables, arrays, linked lists queue Dian Dian stack are all linear table data structure.

Nonlinear Table
nonlinear table data is irregular, with a linear table is the opposite, such as binary heap Dian Dian the like, in the nonlinear table, not a simple relationship between the data before and after.

Advantages: in memory are stored contiguously, indexing speed is very fast, simple assignments and modify elements.

Cons: When a statement must indicate the length of the elements of its storage type, length, the array is too long, will result in a waste of memory, and an array of length is too short, it can cause erroneous data overflow. Array insert, delete elements inefficient.

ArrayList

advantage:

  • When declaring ArrayList does not need to declare its type, length, because the capacity can grow dynamically.
  • When the ArrayList object is stored, abandoned the type of information, all of the objects as shields Object, not compile-time type checking, but will complain runtime.

Disadvantages:

  • ArrayList array expansion is the impact on the efficiency of a large factor.
  • Whenever execution method Add, AddRange, Insert, InsertRange such as adding elements, the capacity will check whether the internal array is not enough, if it is, it will be twice the current capacity to rebuild an array, the old elements into the new Copy array, and then discard the old array, expansion of operations at this critical point, it should be relatively affect efficiency.
  • Not type safe.
  • Process boxing and unboxing is loss of performance.

List collection

  • Is the type of security, a description of the type of data stored.
  • List can not be constructed, but you can create as a reference for the List to the above, and ListArray can be constructed.
  • List the benefits of generics:
      by allowing specify a particular type or method of operation of a generic class, generic function of the type of security tasks from your to the compiler. No need to write code to detect the data type is correct, because it will force the use of the correct data type at compile time. Reducing the possibility of false casts needs and runtime. Generics provide type safety but did not increase the overhead of multiple implementations.

LinkedList

  • LinkedList also List interface implementation class.
  • LinkedList is a doubly linked list. It features linked list data structure is the spatial distribution of each element need not be continuous, insert and delete elements very fast, but the speed is slow access elements.
  • Adding and has better performance than the ArrayList remove elements. But in the query and modify the terms of the elements to be weaker than the ArrayList.

HashTable与HashMap、HashSet

  • Synchronization: Hashtable is thread safe, that is synchronized, and HashMap line program is unsafe, not synchronized.
  • HashMap allowed to null a key, a plurality of the null value.
  • hashtable of key and value are not allowed to be null.
  • HashSet implements the Set interface, the bottom is made to achieve a hash table (actually the HashMap), Set elements inside disorder not repeat, a null value may be allowed.

Two, Handler proper use

private static class  InnerHandler extends Handler{
        private final WeakReference<MainActivity> mActivity;

        private InnerHandler(MainActivity activity) {
            mActivity = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            MainActivity activity = mActivity.get();
            if(activity!=null){
                
            }
        }
    }

Third, the proper use of Context 

The proper use of the singleton 

public class SingleInstance {
    private Context mContext;
    private static SingleInstance sInstance;

    private SingleInstance(Context context) {
        mContext = context;
    }

    public static SingleInstance getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new SingleInstance(context.getApplicationContext());
        }
        return sInstance;
    }
}

 Comparison of Different Context

Four, four master Java reference

A strong reference: java inside the most widely used one, the default is the object of a reference type. If an object has strong references, then the garbage payback period is not to operate it, and when there is insufficient memory space, Java virtual machine will throw an OutOfMemoryError, then the application will terminate.

Soft Quote: If there is only one object soft references, then when sufficient memory space, it will not refuse payback period for recovery operations, only when out of memory, this object will be recovered.

Weak Reference: When the garbage collector scans only a weak reference to an object, whether or not the current memory space is insufficient, will be on the weak reference objects for recycling.

False quote: phantom references will not have any impact on the pointed object life cycle, it will follow the original way is garbage collected, but a phantom reference mark on the role of nature, primarily used to track objects recycled garbage activities virtual reference must be used in conjunction with a reference queue, when the object is garbage, if virtual reference exists, then the entire Java virtual machine will be added to the reference phantom reference associated with the queue.

Fifth, coding practices

  1. XML reduce unnecessary member variables;
  2. Try not to use enumeration, less iterator;
  3. To Cursor, Receiver, Sensor, File and other objects, pay attention to their creation, recovery and registration, the anti-Registration; avoid extensive use of annotations, reflection;
  4. Remember broadcast event cancellation, webview exit interface objects, remember destruction, empty.
  5. Without reference to the object, the blank is null, easy to detect spam memory.
  6. Multi basic data types, less their reference data types. Such as Integer will share larger than int.
  7. Less static variables modified, the modified global variables that can not be recovered GC.
  8. Use StringBuffer replace string concatenation String (with append stitching), String each one more "+", will be more of an object is created.
  9. bitmap, cursor Cursor, IO or file stream, etc. do not, remember to recycle. Especially the picture memory for loading and large, the picture quality can be compressed or physical size.
  10. Avoid creating objects in ondraw method frequently drawn in.
  11. Prevent long-term singleton class holds no reference to the object, try incoming ApplicationContext.
  12. Non-static inner classes cause memory leaks, such as Activity created Handler, you can try to get a weak reference to an external object reference.
  13. Broadcast logout, the page has not been performed Activity exit the Thread of cancellation or Timer also perform regular tasks logout and so on.
  14. Activity end time, the need to cancel out the property animation.
  15. webview exit destruction.

 

"Android Advanced Advanced"

https://www.jianshu.com/p/cd7552bdaf6e

https://blog.csdn.net/zhuolou1208/article/details/78095293

https://blog.csdn.net/qq_30257149/article/details/99588189

Published 49 original articles · won praise 2 · Views 8584

Guess you like

Origin blog.csdn.net/yangjunjin/article/details/105158956