Summary of java Memory Optimization Methods

  • 2021-09-16 06:47:14
  • OfStack

1. Unnecessary automatic packing.

Automatic packing is to convert basic data types into corresponding complex types. The investigation of addition and deletion of HashMap is full of automatic packing problems, so the problems such as replacing SparseArray and ArrrayMap with HashMap should be avoided as much as possible.

2. Memory reuse.

Resource reuse: Common string, color, layout.

View reuse: Optimized reuse similar to RecyclerView.

Target pool: Create a target pool without repeatedly creating a target. Similar to thread pool, messae enjoys meta-mode.

Bitmap object multiplexing: With the inBitmap attribute, the Bitmap decoder can inform the Bitmap decoder to use an existing storage area, and the newly decoded bitmap can try to use the storage area previously occupied by bitmap in heap.

3. When the memory of App is too low, it can release the memory independently.

When the memory of App exiting background is tight and lost by Kill, the method of onTrimmemory/onLowMemory in Application is rewritten to release image cache and static cache.

4. Optimize other scenarios.

item frees the reference to the image when it cannot be recycled.

When using string concatenation, try to use StringBuilder, StringBuffer (memory jitter)

Customizing view reduces the time and execution times of onDraw.

Try to use static inner classes.

Try to use underlying data types.

Use soft/weak references when appropriate.

Content extension:

For programmers, code optimization is a very important topic. Some people may feel useless, 1 some small places have what good to modify, change and do not change the efficiency of the operation of the code has what impact? I think about this question like this, just like a whale in the sea, is it useful to eat a shrimp? It's no use, but after eating more than 1 shrimp, the whale is fed. Code optimization is also one. If the project focuses on going online without BUG as soon as possible, then you can grasp the big and let go of the small at this time, and the details of the code can not be carefully ground; However, if there is enough time to develop and maintain the code, every detail that can be optimized must be considered at this time. The accumulation of one small optimization point will definitely improve the running efficiency of the code. In fact, in fact, the

The goal of code optimization is:

1. Reduce the size of your code

2. Improve the efficiency of code running


Related articles: