Big White Edition Solution:
1. Don't "create garbage" in the loop (temporary object)
Error demonstration:
for (i in 0..100000) { val temp = "Item $i" // New String each loop → Crazy GC!}
The correct way to do it:
val sb = StringBuilder() for (i in 0..100000) { () ("Item ").append(i) // Reuse StringBuilder}
2. Don't decorate (create objects) in onDraw()
Error demonstration:
override fun onDraw(canvas: Canvas) { val paint = Paint() // Every time I draw it, new → memory explodes! ("Hello", 0f, 0f, paint) }
The correct way to do it:
private val paint = Paint() // Initialize in advance override fun onDraw(canvas: Canvas) { ("Hello", 0f, 0f, paint) }
3. Change out the "classic car" that consumes fuel (inefficient data structure)
Scene | Wrong selection | Proper choice | Memory savings |
---|---|---|---|
Map with key int | HashMap<Int, ...> |
SparseArray |
30%+ |
The map with long key | HashMap<Long, ...> |
LongSparseArray |
30%+ |
Key value pairs with only two values | Use class/Map |
Pair Or custom structure |
50% |
4. Avoid the "autoboxing" trap (base type → object)
Error demonstration:
val list = ArrayList<Integer>() (1) // int automatically boxed for Integer → generate additional objects
The correct way to do it:
val list = IntArray(10) // Use basic type arrays directlylist[0] = 1
5. Object Pool: Rent shared bicycles, don’t always buy new ones
Scene: Frequently create similar objects (such as the ViewHolder of RecyclerView)
Code Example:
private val viewHolderPool = <ViewHolder>(10) fun create(): ViewHolder { return () ?: ViewHolder(...) } fun recycle(viewHolder: ViewHolder) { (viewHolder) }
Pit avoidance tool kit:
-
Android Profiler:
- Observe the memory curve → The serrated violent fluctuation is memory jitter
-
LeakCanary:
- Find out the culprit of frequent GCs due to memory leaks
-
StrictMode:
- Turn on thread policy detection and discover the time-consuming object creation of the main thread
Summary of the formula:
To avoid memory jitter, reducing objects is the key
Use temporary workers carefully in the cycle, don't build new ones in onDraw
The data structure is selected with clever choice, automatic packing must be eliminated
Object pooling and reuse are wonderful, and tool detection ensures safety!
The above is the detailed content of Android's solution to avoid memory jitter. For more information about Android's avoid memory jitter, please pay attention to my other related articles!