[Android instance] How to become an android player Article 3

Source: Internet
Author: User

Avoid object Creation

There are no free objects in the world. Although GC creates a temporary object pool for each thread, it can reduce the cost of object creation, but the cost of memory allocation is always higher than that of memory allocation.

If you allocate the object memory in the user interface loop, it will lead to periodic garbage collection, and the user will feel that the interface is as choppy.

Therefore, unless necessary, try to avoid the instance of the object as much as possible. The following example will help you understand this principle:

When you extract a string from user input data, try to use the substring function to obtain a substring of the original data, instead of creating a copy for the substring. In this way, you have a new String object, which shares a char array with the original data.
If you have a function that returns a String object, and you know exactly that the string will be appended to a stringbuffer, change the parameter and implementation method of this function, directly append the result to stringbuffer, instead of creating a short-lived temporary object.
A more extreme example is to divide a multi-dimensional array into multiple one-dimensional arrays.

The Int array is better than the integer array, which also summarizes the basic fact that two parallel int arrays provide much better performance than the array of (INT, INT) objects. Similarly, this is intended for a combination of all basic types.
If you want to use a container to store (Foo, bar) tuples, try to use two separate Foo [] arrays and bar [] arrays, which must be equal to (Foo, bar) array efficiency is higher. (There is also an exception, that is, when you create an API to allow others to call it. At this time, you should pay attention to the design of API excuses and sacrifice a little speed. Of course, you still need to improve the code efficiency as much as possible within the API)

In general, it is to avoid creating short-lived temporary objects. Reduce the creation of objects to reduce the garbage collection, and thus reduce the impact on user experience.

Use local methods

When processing strings, do not use special methods (specialty methods) such as string. indexof () and string. lastindexof ). These methods are implemented using C/C ++, which is 10 to 100 times faster than Java loops.

Good real-time analogy Interface

Suppose you have a hashmap object. You can declare it as a hashmap or map:

Map mymap1 = new hashmap ();
Hashmap mymap2 = new hashmap ();
Which one is better?

In the traditional view, map is better, because you can change its specific implementation class as long as the class inherits from the map interface. The traditional view is correct for traditional programs, but it is not suitable for embedded systems. Calling an interface takes twice as long as calling an object class.

If hashmap is perfect for your program, using map has no value. If you are not sure about some items, avoid using map first, and leave the rest to the refactoring function provided by IDE. (Of course, a public API is an exception: A good API often sacrifices some performance)

Static method is better than virtual Method

If you do not need to access the member variables of an object, declare the method as static. The virtual method runs faster because it can be called directly without a virtual function table. In addition, you can declare that the function call does not change the object state.

Getter and setter are not required

In many local languages such as C ++, getter (for example, I = getcount () is used to avoid direct access to the member variable (I = mcount ). This is a good habit in C ++, because the compiler can be accessed inline. If you need to constrain or debug variables, you can add code at any time.

On Android, this is not a good idea. The overhead of the virtual method is much greater than that of directly accessing the member variable. In the general interface definition, getters and setters can be defined according to the OO method, but in the general class, you should directly access the variable.

Cache member variables locally

Accessing member variables is much slower than accessing local variables. The following code:

Java code

1 For (INT I = 0; I <this. mcount; I ++)

2 dumpitem (this. mitems [I]);

It is best to change it to this:

Java code

3 int COUNT = This. mcount;

4 item [] items = This. mitems;

5 For (INT I = 0; I <count; I ++)

6 dumpitems (items [I]);

(This is used to indicate that these are member variables)

Another similar principle is: Never call any method in the second condition of. As shown in the following method, the getcount () method is called every time a loop is executed, which is much more overhead than saving the result in an int.

Java code

7 For (INT I = 0; I <this. getcount (); I ++)

8 dumpitems (this. getitem (I ));

Similarly, if you want to access a variable multiple times, you 'd better create a local variable for it first, for example:

Java code

9 protected void drawhorizontalscrollbar (canvas, int width, int height ){
10 if (ishorizontalscrollbarenabled ()){
11 int size = mscrollbar. getsize (false );
12 if (size <= 0 ){
13 size = mscrollbarsize;
14}
15 mscrollbar. setbounds (0, height-size, width, height );
16 mscrollbar. setparams (computehorizontalscrollrange (), computehorizontalscroloffset (), computehorizontalscrollextent (), false );
17 mscrollbar. Draw (canvas );
18}
19}

Here, the member variable mscrollbar is accessed four times. If it is cached locally, the four member variable accesses will become four more efficient stack variable accesses.
In addition, the efficiency of method parameters is the same as that of local variables.

Use Constants


Let's take a look at the Declaration of the two paragraphs before the class:

Java code

20 static int intval = 42;
21 static string strval = "Hello, world! ";

It must generate an initialization class method called <clinit>. This method will be executed when the class is used for the first time. The method will assign 42 to intval, and then assign a reference pointing to a common table in the class to strval. When these values are used in the future, they will be found in the member variable table.

Let's make some improvements and use the keyword "final:

Java code

22 static final int intval = 42;
23 static final string strval = "Hello, world! ";

Currently, the <clinit> method is no longer required for classes, because constants are directly saved to class files during member variable initialization. The code that uses intval is directly replaced with 42, and strval points to a String constant instead of a member variable.

Declaring a method or class as "final" will not improve the performance, but will help the compiler optimize the code. For example, if the compiler knows that a "Getter" method will not be overloaded, the compiler will call it inline.

You can also declare the local variable as "final" without performance improvement. Using "final" can only make the local variables look clearer (but sometimes this is required, for example, when using an anonymous internal class) (xing: the original text is or you have, e.g. for use in an anonymous inner class)

Use foreach with caution

Foreach can be used in the collection type that implements the iterable interface. Foreach assigns an iterator to these objects and then calls the hasnext () and next () methods. You 'd better use foreach to process the arraylist object, but for other set objects, foreach is equivalent to using iterator.

The following describes an acceptable foreach usage:

Java code

24 public class Foo {
25 int msplat;
26 static Foo marray [] = new Foo [27];
27
28 public static void zero (){
29 int sum = 0;
30 For (INT I = 0; I <marray. length; I ++ ){
31 sum + = marray [I]. msplat;
32}
33}
34
35 public static void one (){
36 int sum = 0;
37 Foo [] localarray = marray;
38 int Len = localarray. length;
39 For (INT I = 0; I <Len; I ++ ){
40 sum + = localarray [I]. msplat;
41}
42}
43
44 public static void two (){
45 int sum = 0;
46 for (foo a: marray ){
47 sum + = A. msplat;
48}
49}
50}

In zero (), each loop accesses two static member variables to obtain the length of an array.
Retrieves the static field twice and gets the array length once for every iteration through the loop.

In one (), all member variables are stored locally.
Pulls everything out into local variables, avoiding the lookups.

Two () uses the foreach syntax introduced in java1.5. The compiler saves the array reference and length to the local variable, which is very good for accessing array elements. However, the compiler will also generate an additional storage operation on local variables (access to variable A) in each loop, which will be 4 bytes more than one, the speed is a little slower.

To sum up, the foreach syntax has good performance when used in array, but be careful when used in other set objects because it produces additional objects.

Avoid Enumeration

It is very convenient to enumerate variables, but unfortunately it will sacrifice the execution speed and greatly increase the file size. For example:

Public class Foo {public Enum shrubbery {ground, crawler, hanging }}

A 900-byte. Class file (FOO $ shubbery. Class) is generated ). When it is called for the first time, this class will call the initialization method to prepare each enumerated variable. Each enumeration item is declared as a static variable and assigned a value. Put these static variables in a static array variable named "$ values. So much code is just to use three integers.

In this way:

Shrubbery shrub = shrubbery. Ground; will cause a reference to the static variable. If the static variable is final int, the compiler will directly inline this constant.

On the one hand, using enumeration variables can make your API better and provide compile-time checks. Therefore, in general, you should select an enumeration variable for the public API. However, when performance is limited, you should avoid this practice.

In some cases, it is better to use the ordinal () method to obtain the integer of the enumerated variable. For example, we will:

Java code

51 for (INT n = 0; n <list. Size (); N ++ ){
52 If (list. items [N]. E = myenum. val_x) // do stuff 1
53 else if (list. items [N]. E = myenum. val_y) // do stuff 2
54}

Replace:
Java code

55 int valx = myenum. val_x.ordinal ();
56 int Valy = myenum. val_y.ordinal ();
57 int COUNT = List. Size ();
58 myitem items = List. Items ();
59 for (INT n = 0; n <count; n ++ ){
60 int valitem = items [N]. E. ordinal ();
61 If (valitem = valx) // do stuff 1
62 else if (valitem = Valy) // do stuff 2
63}

It will improve the performance, but this is not the final solution.
Declare the variables used with the internal class within the package range.
See the following class definitions:

Java code

64 public class Foo {
65 private int mvalue;
66 public void run (){
67 inner in = new inner ();
68 mvalue = 27;
69 in. Stuff ();
70}
71
72 private void dostuff (INT value ){
73 system. Out. println ("value is" + value );
74}
75
76 private class inner {
77 void stuff (){
78 Foo. This. dostuff (FOO. This. mvalue );
79}
80}
81}

The key here is that we define an internal class (FOO $ inner) that needs to access the private domain variables and functions of the external class. This is legal and will print the expected result "value is 27 ".

Technically (behind the scenes) Foo $ inner is a completely independent class, and it is illegal to directly access the private members of foo. To bridge this gap, the compiler must generate a set of methods:

Java code

82 static int Foo. Access $100 (Foo ){
83 return Foo. mvalue;
84}
85
86 static void Foo. Access $200 (Foo, int value ){
87 Foo. dostuff (value );
88}

Each time an internal class accesses the "mvalue" and "dostuff" methods, these static methods are called. That is to say, the code above illustrates a problem where you access these member variables and functions through interface methods rather than directly calling them. As we have mentioned earlier, the use of interface methods (getter and setter) is slower than the direct access speed. Therefore, this example is a "implicit" performance obstacle under a specific syntax.

We can avoid this problem by changing the variable and function declaration for internal class access from private range to package range. This can make the code run faster and avoid generating additional static methods. (Unfortunately, these domains and methods can be directly accessed by other classes in the same package, which is contrary to the classic oo principle. Therefore, you should use this optimization principle with caution when designing public APIs)

Avoid floating point number

Before the emergence of the Pentium CPU, the game designers did the most integer operations. With the arrival of the Pentium, the floating point computing processor has become a built-in feature of the CPU. The use of floating point and integer can make your game run more smoothly. Generally on a desktop computer, you can use floating point operations at will.

Unfortunately, embedded processors generally do not have hardware that supports floating-point operations. All operations on "float" and "double" are implemented through software. Some basic floating point operations can be completed in milliseconds.

It is even an integer. Some chips have hardware support for multiplication but lack Division support. In this case, the division and modulo operations of integers are also completed by software. Therefore, be cautious when using hash tables or performing a large number of mathematical operations. "

5. learn at least one server-side Development Technology

Some may ask: why do I need to learn at least one server development technology to learn about Android Application Development? The answer is as follows: on the one hand, Android claims to be the first mobile software that is truly open and complete for mobile terminals. As a mobile terminal, it must be combined with the server to play a huge role. In short, the cloud + cloud approach is required. Android is tailored for the mobile Internet era. The service model in the mobile Internet era is "mobile terminal + Internet + application software ", android, one of the application technologies in the mobile Internet era, is only used to develop mobile terminal software, while server technology is used to develop Internet applications, in the future, the mainstream application modes of software in the mobile Internet era will be "mobile client + Internet Application Server ", this mode requires mobile Internet developers to Master not only mobile terminal software technologies such as Android, but also the server technologies used to develop Internet applications. At present, software enterprises generally have such problems. programmers who develop Android terminal software on the mobile Internet do not understand web application technology, while programmers who develop web applications do not understand mobile terminal technology, in this way, the connection between the client and the server is faulty. The current situation is: programmers who master both mobile Internet Android terminal technology and Web application technology are scarce. As China enters the mobile Internet era, enterprises have a strong demand for comprehensive talent in the mobile Internet era. If you do not understand the web application technology, you will eventually encounter technical and development bottlenecks. On the other hand, one of the true advantages launched by Google and Oha lies in the integration with the Internet, one of Google's intentions is to open up new terminals to use Google's advantageous services.
Currently, the mainstream server development technologies include sun's Java EE, Microsoft's. net, and open-source lamp systems represented by PHP and MySQL. Which one should we choose? Theoretically, many people tend to choose Java ee. After all, they use Java as the development language, but many people are afraid of the numerous Java EE frameworks, in fact, you can start with Struts when learning Java EE, and gradually deepen with the business needs. Of course, you can also select Microsoft's. net. After all, this technology system also occupies a large market share. In fact, I believe that lamp can be the most cost-effective. On the one hand, PHP is the mainstream Web language, most new websites, especially entrepreneurial websites, generally use PHP as the server development language. On the other hand, we have mentioned that android is born for mobile Internet, the two have achieved a perfect fit.


This article from: http://www.eoeandroid.com

Related Article

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.