Java code optimization for Android Optimization

Source: Internet
Author: User

1. You can use the cache if you need to use many objects.Users who often write Java may use hashmap to implement cache. However, when the key is an integer value, Android defines a more efficient class: sparsearray class, it is more efficient than hashmap.

2. Different API versions have been optimized for different functions. Some functions are discarded and new calling functions are enabled. Therefore, when different api versions are implemented, different levels of optimization can be performed for different APIs. I personally think this optimization is costly and has low benefits.For example, sparsearray is optimized in Honeycomb. Therefore, when using a later version of SDK, use new functions and use old compatible functions for earlier versions.

If (build. version. sdk_int> = build. version_codes.honeycomb) {sparsearray. removeat (1); // API level 11 and above} else {int key = sparsearray. keyat (1); // The default implementation efficiency is lower than that of sparsearray. remove (key );}


3. performance not only indicates the execution speed of the program, but also the user interaction experience and the response speed when the user uses the software. The UI thread is used to process key messages (for example, view. onkeydown () or activity. onkeylongpress (), graphical painting (such as: View. ondraw () and the occurrence of the lifecycle (such as oncreate () and onstart (). Other unimportant code should be processed by non-UI threads as much as possible, avoid ANR (Application
Not responding.

In an activity, it is very important to minimize the startup time of the activity, and to minimize the time-consuming operations in oncreate (), onstart (), onresume (), for example, the oncreate () method of activeity generally uses setcontentview or other methods to add the inflate view. The inflate view process is time-consuming, so the UI interface design is very important, in XML, try to use a concise layout to reduce the loading time of the layout. There are some common operations, such:

(1) Replace linearlayout with relativelayout

(2) Try to use viewroot for delayed loading of view layout to accelerate UI display.

For more information, see my previous article: tips from Android SDK articles


4. Low network speed and I/O operations should be handled for network and file operations. SD cards have different processing speeds.If our program depends on the performance of the SD card, we must focus on testing the SD card of different manufacturers.
5. After 2.3, you can use strictmode to assist in testing program user experience and program robustness at low speed or in other situations. Note that this is only used during development, release versions must be removed.For example, the efficiency of code execution is low:

public static BigInteger computeRecursivelyWithCache(int n){StrictMode.noteSlowCall(“computeRecursivelyWithCache”); // message can beanythingSparseArray<BigInteger> cache = new SparseArray<BigInteger>();return computeRecursivelyWithCache(n, cache);}…}

6. Database Optimization

When using databases, we often use the create table and insert into statements. For example:

SQLiteDatabase db = SQLiteDatabase.create(null); db.execSQL(“CREATE TABLE cheese (name TEXT, origin TEXT)”);db.execSQL(“INSERT INTO cheese VALUES (‘Roquefort’, ‘Roquefort-sur-Soulzon’)”);db.close(); 

It takes some time to execute SQLite statements. These statements need:Interpret, compile, or executeIn addition, string is immutable. Therefore, many object creation operations are performed when the statement is formed, resulting in performance problems. Here we will give an example to illustrate in detail:

public class Cheeses {private static final String[] sCheeseNames = {“Abbaye de Belloc”,“Abbaye du Mont des Cats”,…“Vieux Boulogne”};private static final String[] sCheeseOrigins = {“Notre-Dame de Belloc”,“Mont des Cats”,…“Boulogne-sur-Mer”};private final SQLiteDatabase db;public Cheeses () {db = SQLiteDatabase.create(null); // memory-backed databasedb.execSQL(“CREATE TABLE cheese (name TEXT, origin TEXT)”);}public void populateWithStringPlus () {int i = 0;for (String name : sCheeseNames) {String origin = sCheeseOrigins[i++];String sql = “INSERT INTO cheese VALUES(\”” + name + ”\”,\”” + origin +”\”)”;db.execSQL(sql);}}}

When populatewithstringplus is executed, a large number of string objects are created and execute execsql. The most obvious optimization method for the first point isUse the string. format or stringbuilder instead of the string + operation:

public void populateWithStringFormat () {int i = 0;for (String name : sCheeseNames) {String origin = sCheeseOrigins[i++];CHAPTER 1: Optimizing Java Code 27String sql = String.format(“INSERT INTO cheese VALUES(\”%s\”,\”%s\”)”, name,origin);db.execSQL(sql);}}public void populateWithStringBuilder () {StringBuilder builder = new StringBuilder();builder.append(“INSERT INTO cheese VALUES(\””);int resetLength = builder.length();int i = 0;for (String name : sCheeseNames) {String origin = sCheeseOrigins[i++];builder.setLength(resetLength); // reset positionbuilder.append(name).append(“\”,\””).append(origin).append(“\”)”); // chaincallsdb.execSQL(builder.toString());}}

When 650 pieces of data are added, String. format takes 371 ms, while stringbuilder takes ms. The latter is more efficient, but not obvious.

The second method of optimization: because each insert statement is similar, but the data changes, you canUse compilestatement to create statements for reuse. Only one statement is compiled outside the loop:

public void populateWithCompileStatement () {SQLiteStatement stmt = db.compileStatement(“INSERT INTO cheese VALUES(?,?)”);int i = 0;for (String name : sCheeseNames) {String origin = sCheeseOrigins[i++];stmt.clearBindings();stmt.bindString(1, name); // replace first question mark with namestmt. bindString(2, origin); // replace second question mark with originstmt.executeInsert();}}

In this method, the SQL statement is compiled only once, instead of 650 times. The optimized time is only 268 Ms.

8. Try to read only the required data when reading the database. Do not read all the data.

Public void iteratebothcolumns () {cursor c = dB. query ("cheese", null, null); If (C. movetofirst () {do {} while (C. movetonext ();} C. close ();} public void iteratefirstcolumn () {cursor c = dB. query ("cheese", new string [] {"name"}, null, null); // If (C. movetofirst () {do {} while (C. movetonext ();} C. close ();}

For example, if the first method reads all data, and the second method reads name data, the latter takes less time than the former.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.