Those familiar with Android custom Views probably know:

Do not create objects in onDraw

The reasons are:

OnDraw () is called fast and high frequency –> fast and frequent memory requisition –> frequent GC–> thread hangs –> UI freezes

Of course, the above reasons are important and correct, there is nothing to say. Because it’s clearly written in onDraw(), you can see it immediately. What you see is what you get.

Here’s a hidden cost that’s easily overlooked (or completely unknown) :

We overwrite the onDraw() method to customize the View, creating objects that are likely to be Paint, Path, Typeface, etc. In onDraw(), the Canvas API is called to draw the desired image. The actual drawing operation actually calls the underlying C++ code (Skia/OpenGL ES). As mentioned above, Paint and other objects are native objects that encapsulate the C++ layer.

“What? C++?”


. The logic is simple

C++ is called native because it does not manage memory automatically (no garbage collector, manage memory manually), and programs need to explicitly call destructors to destroy objects to reclaim memory. At this time, finalizer(nativeObject) can only be used with Java Finalize () method, while Java Finalize () method is designed to be called before garbage collection. This means that the Java objects that were created in large numbers before being recycled have to execute code in finalize() method first, which leads to the main thread stuttering further.

Also, the destructor call locks the native heap. What does that mean? The actual drawing process can also be blocked by high frequency, an effect that was seen in the main thread before Android5.0 and in the RenderThread after Android5.0, further aggravating the lag.

Seeing this, some friends may ask:

Well, that sounds pretty fancy, but what do I know about that?

I definitely won’t create objects in onDraw(), and I won’t have this problem!

In fact, today’s content is to extend, to have some understanding of the underlying dependency, it often does not implement in the way we expect, the reason why I want to write today’s content, because I think of my own plug-ins encountered in the practice of native cache, is also painstakingly solved.


reference

www.youtube.com/watch?v=HAK…