In programming development, memory usage is a reality we often have to face. The usual direction of memory tuning is to minimize memory usage. Avoiding the creation of unnecessary objects is an important aspect of this. Android devices do not have as much memory as PCs, and the memory occupied by a single App is actually relatively small. Therefore, it is particularly important to avoid creating unnecessary objects for Android development. This article will introduce some common scenarios and methods for avoiding object creation. Some of them are micro-optimizations, some are coding techniques, and of course there are methods that can really have a significant effect. Using Singleton Singleton is a common design pattern. Using this pattern, we can only provide one object for global call. Therefore, singleton is a way to avoid creating unnecessary objects. The singleton pattern is easy to use, but you need to pay attention to many issues. The most important thing is to ensure the uniqueness of the singleton in the case of multi-threaded concurrency. Of course, there are many ways, such as the hungry man style and lazy man style double-check. Here is a very geeky way to write a singleton.
In Java, static initialization of a class is triggered when the class is loaded. By using this principle, we can take advantage of this feature and combine it with inner classes to implement the above code and create instances in a lazy way. Avoid implicit boxing Automatic boxing is a feature introduced in Java 5, which automatically converts primitive data into corresponding reference types, such as converting int to Integer. This feature greatly reduces the tedious work of coding, but if you are not careful, you may create unnecessary objects. For example, the following code
The code sum+=i above can be seen as sum = sum + i, but the + operator is not applicable to Integer objects. First, sum performs an automatic unboxing operation to add the values, and finally an automatic boxing operation occurs to convert it into an Integer object. The internal changes are as follows
Since the sum we declare here is of Integer type, nearly 4,000 useless Integer objects will be created in the above loop. In such a large loop, the performance of the program will be reduced and the workload of garbage collection will be increased. Therefore, when we program, we need to pay attention to this point and declare the variable type correctly to avoid performance problems caused by automatic boxing. In addition, when adding primitive data types to a collection, automatic boxing will also occur, so objects are created in this process. If you need to avoid this, you can choose containers such as SparseArray, SparseBooleanArray, SparseLongArray, etc. Choose your container carefully Java and Android provide many editable container collections to organize objects, such as ArrayList, ContentValues, HashMap, etc. However, although such containers are convenient to use, they also have some problems, that is, they will automatically expand, which does not create a new object, but creates a larger container object. This means that this will take up more memory space. Taking HashMap as an example, when we put key and value, it will detect whether it needs to be expanded. If necessary, it will double the capacity.
Regarding the issue of capacity expansion, there are usually the following methods
Make good use of LaunchMode The LaunchMode is definitely related to the Activity. Normally, we declare the Activity in the manifest, and if we don't set the LaunchMode, the default standard mode is used. Once set to standard, a new instance of Activity will be created every time an Intent is requested. For example, if there are 10 intents to compose emails, 10 instances of ComposeMailActivity will be created to handle these intents. As a result, it is obvious that this mode will create multiple instances of an Activity. If you are looking for an Activity with a search function, you only need to keep one Activity instance. Using the standard mode will cause too many Activity instances to be created, which is not a good idea. Ensure that LaunchMode is used reasonably and in accordance with common sense to reduce the creation of Activities. Activity handles onConfigurationChanged This is another one about creating Activity objects, because the cost of creating Activity is much higher than other objects. By default, when we rotate the screen, the original Activity will be destroyed and a new Activity will be created. This is done to handle layout adaptation. Of course, this is the system's default approach. In the case of controllable development, we can avoid recreating the Activity. Taking screen switching as an example, when declaring Activity, add
Then override the onConfigurationChanged method of Activity
Note the string concatenation Strings are perhaps the least noticeable item. Here we mainly talk about string concatenation
This should be our most common way of logging. However, string concatenation actually generates a StringBuilder object, and then appends them one by one until the toString method is finally called. The following is a code loop, which is obviously very bad because it creates many StringBuilder objects.
Ways to reduce string concatenation include
Reduce layout levels Too many layout levels not only make the inflation process time-consuming, but also create redundant auxiliary layouts. Therefore, it is necessary to reduce auxiliary layouts. You can try other layout methods or customize views to solve such problems. Check in advance to reduce unnecessary exceptions Exceptions are common in programs, and the code for exceptions is actually very high because it needs to collect the on-site data stacktrace. However, there are still some measures to avoid exceptions, that is, to do some advance checks. For example, if we want to print each line of a string in a file, the unchecked code is as follows, and there is a possibility that FileNotFoundException will be thrown.
If we check whether the file exists, the probability of throwing FileNotFoundException will be much reduced.
The above check is a good coding technique and is recommended to be adopted. Don't create too many threads In Android, we should try to avoid performing time-consuming operations in the main thread, so we need to use other threads.
Although these work, the cost of creating a thread is much higher than that of a normal object. It is recommended to use HandlerThread or ThreadPool as a replacement. Use annotations instead of enumerations Enumeration is a method we often use to limit values. It is more reliable to use enumeration than simple constant convention. However, the essence of enumeration is to create objects. Fortunately, Android provides relevant annotations, which allows value limitation to be performed at compile time, thereby reducing the pressure at runtime. The relevant annotations are IntDef and StringDef. The following uses IntDef as an example to introduce how to use In a file declare
Then set up a method that writes something like this
Only STATE_OPEN, STATE_CLOSE, and STATE_BROKEN can be used when calling methods. Using other values will result in compiler reminders and warnings. Select object pool There are many pool concepts in Android, such as thread pool, connection pool, including Handler.Message, which we have been using for a long time, which uses the pool technology. For example, if we want to use Handler to send a message, we can use Message msg = new Message() or Message msg = handler.obtainMessage(). Using a pool does not create a new object every time, but rather takes objects from the pool first. There are a few things to note when using object pools
Initialize Application Carefully Android applications can support opening multiple processes. The usual practice is as follows
Usually we will do a lot of initialization operations in the onCreate method of Application, but each process startup needs to execute this onCreate method. In order to avoid unnecessary initialization, it is recommended to initialize according to the process (by judging the current process name).
The above knowledge is a summary of how to avoid creating redundant objects in Android. You are welcome to put forward your opinions and views and make progress together. |
<<: Losing both hardware and software: Why is Apple's licensing of operating systems a "dirty move"?
>>: What are the shortcomings of Android compared to iOS?
In recent days, the Google Glass incident has att...
On the Internet, we should regard advertising con...
For a large, mature company, promoting a new prod...
I often hear that there are four stages of learni...
C-end products are still different from B-end pro...
recent A six-month-old snow leopard refused to le...
After sending a voice message on WeChat, will you...
When we are doing product or brand marketing , it...
Procreate painting course resources introduction:...
Although vivo has added multiple product lines in...
What is the price for developing a hardware mini ...
Produced by: Science Popularization China Author:...
People often ask: Is blood type related to cancer...
I used to think about this question often when I ...