Web Front-end
Front-end Q&A
11 Android performance optimization interview questions [with answers]11 Android performance optimization interview questions [with answers]
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?
#4. How does Bitmap handle large images, such as a 30M image, and how to prevent OOM?
- 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.
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:
- Reference answer:
6. What is the difference between memory leak and memory overflow? Are there any tools in AS that can detect memory leaks?
- There are two mechanisms for determining the recyclability of memory objects:
There are four GC recycling algorithms:
- 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
- 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
Old generation : High object survival rate. Using the "Mark-Sweep Algorithm" or "Mark-Sweep Algorithm" only requires marking fewer recycling objects.: 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
- 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
- Memory overflow (out of memory)
7. Performance optimization, how to ensure that the application starts without lag? How to deal with black and white screens?: 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
- 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:##10. What is the adapter of ListView?
- 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
- 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!
React: The Power of a JavaScript Library for Web DevelopmentApr 18, 2025 am 12:25 AMReact is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and
React's Ecosystem: Libraries, Tools, and Best PracticesApr 18, 2025 am 12:23 AMThe React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.
React and Frontend Development: A Comprehensive OverviewApr 18, 2025 am 12:23 AMReact is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability
The Power of React in HTML: Modern Web DevelopmentApr 18, 2025 am 12:22 AMThe application of React in HTML improves the efficiency and flexibility of web development through componentization and virtual DOM. 1) React componentization idea breaks down the UI into reusable units to simplify management. 2) Virtual DOM optimization performance, minimize DOM operations through diffing algorithm. 3) JSX syntax allows writing HTML in JavaScript to improve development efficiency. 4) Use the useState hook to manage state and realize dynamic content updates. 5) Optimization strategies include using React.memo and useCallback to reduce unnecessary rendering.
Understanding React's Primary Function: The Frontend PerspectiveApr 18, 2025 am 12:15 AMReact's main functions include componentized thinking, state management and virtual DOM. 1) The idea of componentization allows splitting the UI into reusable parts to improve code readability and maintainability. 2) State management manages dynamic data through state and props, and changes trigger UI updates. 3) Virtual DOM optimization performance, update the UI through the calculation of the minimum operation of DOM replica in memory.
Frontend Development with React: Advantages and TechniquesApr 17, 2025 am 12:25 AMThe advantages of React are its flexibility and efficiency, which are reflected in: 1) Component-based design improves code reusability; 2) Virtual DOM technology optimizes performance, especially when handling large amounts of data updates; 3) The rich ecosystem provides a large number of third-party libraries and tools. By understanding how React works and uses examples, you can master its core concepts and best practices to build an efficient, maintainable user interface.
React vs. Other Frameworks: Comparing and Contrasting OptionsApr 17, 2025 am 12:23 AMReact is a JavaScript library for building user interfaces, suitable for large and complex applications. 1. The core of React is componentization and virtual DOM, which improves UI rendering performance. 2. Compared with Vue, React is more flexible but has a steep learning curve, which is suitable for large projects. 3. Compared with Angular, React is lighter, dependent on the community ecology, and suitable for projects that require flexibility.
Demystifying React in HTML: How It All WorksApr 17, 2025 am 12:21 AMReact operates in HTML via virtual DOM. 1) React uses JSX syntax to write HTML-like structures. 2) Virtual DOM management UI update, efficient rendering through Diffing algorithm. 3) Use ReactDOM.render() to render the component to the real DOM. 4) Optimization and best practices include using React.memo and component splitting to improve performance and maintainability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools









