Home >Web Front-end >Front-end Q&A >11 Android performance optimization interview questions [with answers]

11 Android performance optimization interview questions [with answers]

藏色散人
藏色散人forward
2020-07-31 14:04:324579browse

Recommended: "2020 Android Interview Questions Summary [Collection]"

Because the actual development and reference answers will be different Different, and I’m afraid of misleading everyone, so I’d better understand the answers to these interview questions by myself! The interviewer will ask questions from the shallower to the deeper knowledge points mentioned in the resume, so don't memorize the answers and understand more.

1. In the third-level cache of images, images are loaded into memory. What will happen if the memory is about to burst? How to deal with it?

  • Reference answer:
    • First of all, we need to know how the third-level cache of images is

      Do not recycle if there is enough memory. When the memory is not enough, the soft reference object is recycled

2. If a 500*500 png high-definition picture is loaded into the memory .How much memory should be occupied?

  • Reference answer:
    • If the screen ratio is not considered: Memory occupied=500 * 500 * 4 = 1000000B ≈ 0.95MB
    • If you consider the screen ratio: Memory occupied = width pixels x (inTargetDensity / inDensity) x height pixels x (inTargetDensity / inDensity) x one The memory byte size occupied by pixels

inDensity represents the dpi of the target image (in which resource folder it is placed), inTargetDensity represents the target screen dpi

3. Performance optimization of WebView?

  • Reference answer:
    • In the process of loading a web page, native, network, back-end processing, and CPU will all participate, and each has necessary work and dependencies; allowing them to process each other in parallel instead of blocking each other can make the web page load faster:
      • WebView initializes slowly. You can request data first during initialization so that the backend and network are not idle.
      • Commonly used JS localization and lazy loading, after using a third party to browse the kernel
      • The end processing is slow, the server can be divided into trunks for output, and the front end also loads network static resources while the back end is calculating.
      • #If the script executes slowly, let the script run at the end without blocking page parsing.
      • #At the same time, reasonable preloading and precaching can reduce the bottleneck of loading speed.
      • WebView is slow to initialize, so initialize a WebView for use at any time.
      • The DNS and link are slow, try to find a way to reuse the domain name and link used by the client.

#4. How does Bitmap handle large images, such as a 30M image, and how to prevent OOM?

    Reference answer: To avoid OOM problems, you need to manage the loading of large images, mainly through scaling to reduce the memory usage of images.
    • The four methods for loading images provided by BitmapFactory (
    • decodeFile, decodeResource, decodeStream, decodeByteArray) all support the BitmapFactory.Options parameter. You can easily sample an image through the inSampleSize parameter. Zoom
    • For example, a high-definition picture of 1024
    • 1024. Then the memory it occupies is 102410244, which is 4MB. If inSampleSize is 2, then the sampled picture occupies only 5125124, which is 1MB (Note: According to the latest official documentation, the value of inSampleSize should always be an exponent of 2, that is, 1, 2, 4, 8, etc. If the external input is less than an exponent of 2, the system will default to the one closest to 2. Replace with an index, such as 2*)
    • comprehensively considered. The image can be loaded effectively through the sampling rate. The process is as follows
      • Set the inJustDecodeBounds parameter of BitmapFactory.Options to true and load the image
      • Get the original width and height information of the image from BitmapFactory.Options, which correspond to the outWidth and outHeight parameters
      • According to the rules of the sampling rate and combined with the needs of the target View The size calculates the sampling rate inSampleSize
      • Set the inJustDecodeBounds parameter of BitmapFactory.Options to false and reload the image

5. Memory recycling mechanism and GC algorithm (the advantages of various algorithms Disadvantages and application scenarios); GC principle timing and GC objects

  • Reference answer:
    • There are two mechanisms for determining the recyclability of memory objects:
      • Reference Counting Algorithm: Add a reference counter to the object. Whenever there is a reference to it, the counter value is increased by 1; when the reference expires, the counter value is decremented by 1; for objects with a counter of 0 at any time It just can't be used again. However, the reference counting algorithm is not used to manage memory in mainstream Java virtual machines. The main reason is that it is difficult to solve the problem of circular references between objects, so another object survival determination algorithm has emerged.
      • reachability analysis method
      • : Use a series of objects called "GCRoots" as the starting point, search downwards from these nodes, and search for the path along the way. The path passed is called Reference chain. When an object has no reference chain connected to GC Roots, it proves that the object is unavailable. Among them, the objects that can be used as GC Roots: objects referenced in the virtual machine stack, mainly refer to local variables in the stack frame and Native# in the local method stack. ##Objects referenced by methods, objects referenced by class static properties in the method area, objects referenced by constants* in the method area
    • There are four GC recycling algorithms:
    • Generational collection algorithm
        : is the current An algorithm used by commercial virtual machines divides the Java heap into the new generation and the old generation based on the different life cycles of objects, and uses the most appropriate collection algorithm based on the characteristics of each generation.
      • New generation: A large number of objects die, and only a few survive. Using the "copy algorithm", only a small number of surviving objects need to be copied.
      • Copy algorithm
          : Divide the available memory into two blocks of equal size according to capacity, and only use one block at a time. When this block of memory is used up, "copy" the surviving objects to another block, and then clean up this block of memory space at once.
        • Simple implementation and efficient operation. When the object survival rate is high, more copy operations will be performed, and the efficiency will become lower
      • Old generation : High object survival rate. Using the "Mark-Sweep Algorithm" or "Mark-Sweep Algorithm" only requires marking fewer recycling objects.
      • Mark-clear algorithm
          : First "mark" all objects that need to be recycled, and then "clear" all marked objects uniformly.
        • The efficiency of both marking and clearing processes is not high. After clearing, a large number of discontinuous memory fragments will be generated. Too many space fragments may cause insufficient space to be found when larger objects need to be allocated during program running. Contiguous memory has to trigger another garbage collection action in advance.
        • Marking-organizing algorithm
        • : First "mark" all the objects that need to be recycled, and then "organize" them so that the surviving objects are all moved to one end. Move, and finally clean up the memory outside the end boundary directly.
        • The mark deflation algorithm will move all surviving objects to one end and process non-surviving objects, so it will not produce memory fragmentation
  • 6. What is the difference between memory leak and memory overflow? Are there any tools in AS that can detect memory leaks?

Reference answer:
  • Memory overflow (out of memory)
      : refers to when the program applies for memory , there is not enough memory space for it to use, and out of memory appears; for example, if you apply for an integer, but save it with a number that can only be saved by a long, that is a memory overflow.
    • Memory leak(memory leak)
    • : It means that after the program applies for memory, it cannot release the applied memory space. The harm of a memory leak can be ignored, but the memory The consequences of leakage and accumulation are very serious. No matter how much memory is available, it will be occupied sooner or later.
    • Memory leak will eventually lead to out of memory!
    • To find memory leaks, you can use the
    • AndroidProfiler
    • tool that comes with Android Studio or
    • MAT
  • 7. Performance optimization, how to ensure that the application starts without lag? How to deal with black and white screens?
  • Reference answer:
    • The application startup speed depends on what you do in the application. For example, you have integrated a lot of sdk, and the sdk The init operation needs to be implemented in the main thread, so there will be a feeling of lag. If not necessary, you can delay loading or start sub-thread processing
    • In addition, the two major factors that affect interface lag areInterface drawing and data processing.
      • Layout optimization (use include, merge tags, it is recommended to use ConstraintLayout for complex layouts, etc.)
      • No time-consuming operations are performed in onCreate() to display the page The View is subdivided and displayed gradually in AsyncTask. It is better to use Handler. In this way, what the user sees is a hierarchical and step-by-step display of Views. They will not see a black screen first and then display all Views at once. It's better to make it an animation, the effect will be more natural.
      • The purpose of using multi-threading is to reduce the time of onCreate() and onReume() as much as possible, so that users can see and operate the page as soon as possible.
      • Reduce the main thread blocking time.
      • Improve the efficiency of Adapter and AdapterView.
    • Cause of black and white screen: When we start an application, the system will check whether it already exists If such a process does not exist, the system service will first check the intent information in startActivity, then create the process, and finally start Actitivy, which is a cold start. The problem of white and black screen at startup occurs during this period. Before the system draws the page and loads the layout, it will first initialize the window (Window). During this step, the system will specify its Theme theme color according to the Theme we set. The settings we set in Style determine the displayed color. Is it a white screen or a black screen.
      • windowIsTranslucent and windowNoTitle, set both properties to true (there will be obvious lag experience, not recommended)
      • If the startup page is just a picture picture, then set a new theme specifically for the launch page, set the theme's android:windowBackground attribute to the launch page background image
      • Use layer-list to create a picture launcher_layer. xml, set it as the background of the launch page dedicated theme, and set it as the background of the launch page layout.

8. If the strong reference is set to null, will it be recycled?

  • Reference answer:
    • The memory occupied by the object will not be released immediately. If the reference of the object is set to null, it only disconnects the reference to the object in the current thread stack frame, and the garbage collector is a thread running in the background. Only when the user thread runs to the safe point (safe point) ) or safe area will scan the object reference relationship. If the object is not referenced, the object will be marked. At this time, the object memory will still not be released immediately because some objects are recoverable (the reference is restored in the finalize method). Only when it is determined that the reference to the object cannot be restored will the object memory be cleared.

9. The difference between ListView and RecyclerView

  • Reference answer:
    • Animation difference:
      • In RecyclerView, there are many animation APIs built in, such as: notifyItemChanged(), notifyDataInserted(), notifyItemMoved(), etc.; if you need to customize the animation effect, You can complete the custom animation effect by implementing (RecyclerView.ItemAnimator class), and then call RecyclerView.setItemAnimator();
      • But ListView does not implement the animation effect, but We can implement the animation effect of the item in the Adapter ourselves;
    • Refresh difference:
      • Usually refreshing data in ListView is Using global refresh notifyDataSetChanged() will consume a lot of resources; itself cannot implement local refresh, but if you want to implement local refresh in ListView, it can still be achieved. When When an item data is refreshed, we can implement an onItemChanged() method in the Adapter, obtain the position of the item in the method (can pass getFirstVisiblePosition()), and then call the getView() method to refresh the item data;
      • Partial refresh can be implemented in RecyclerView, for example: notifyItemChanged();
    • ##Cache difference :
      • RecyclerView has two more levels of cache than ListView, supports multiple separate ItemView caches, supports developers’ customized cache processing logic, and supports all RecyclerViews sharing the same RecyclerViewPool (cache pool).
      • The caching mechanisms of ListView and RecyclerView are basically the same, but the cache usage is different
##10. What is the adapter of ListView?

Reference answer:

  • BaseAdapter: Abstract class. In actual development, we will inherit this class and rewrite related methods. It is the most commonly used adapter!
  • ArrayAdapter: Supports generic operations. The simplest adapter can only display one line of text~
  • SimpleAdapter: An adapter that also has good scalability and can customize a variety of effects!
  • SimpleCursorAdapter: A listView used to display simple text types. It is generally used in databases, but it is a bit outdated and is not recommended!

11. Performance comparison of LinearLayout, FrameLayout, and RelativeLayout. Why?

  • Reference answer:
    • RelativeLayout will make the sub-View call onMeasure twice, and LinearLayout will also call the sub-View onMeasure twice when it has weight
    • If the height of the sub-View of RelativeLayout is different from that of RelativeLayout, it will cause efficiency problems. When the sub-View is complex, this problem will be more serious. If possible, try to use padding instead of margin.
    • Use LinearLayout and FrameLayout instead of RelativeLayout without affecting the depth of the hierarchy.

The above is the detailed content of 11 Android performance optimization interview questions [with answers]. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete