Code optimization: Learn Java and see Android

Source: Internet
Author: User

as a result of the exam, for a long time have not been able to write blog (when out of the Csdn-markdown editor), today on the code optimization aspect to write a blog post, mainly about Java .

The quality of good code:

1. Concise

2. Strong readability

3. Modular

4. Level of

5. Good design

Spend some time designing your program, because the cost of thinking is less than debugging.

6. Efficient

7. Clear

Clarity is fundamental to good code.

Common Programming Specifications:

1. Basic Requirements

* The program structure is clear and easy to understand, the number of program lines of a single function should not exceed 100 lines.

* Use standard functions and public functions as much as possible.

* Do not arbitrarily define global variables, use local variables as much as possible.

* Use parentheses to avoid ambiguity.

2. Requirements for readability

* Readability first, efficiency second.

* Keep comments exactly the same as the code.

* Each source program file, there is a header file description.

* Each function has a function header description.

* When defining or referencing a major variable, note that it can reflect its meaning.

* Constants are defined with a corresponding comment description.

* Use indentation to display the program's logical structure, the indent amount is consistent and in the TAB key unit.

3. Structural Requirements

* Avoid multiple exits from the loop.

* Function has only one exit.

* Conditional assignment statements are not used.

* Do not easily replace logical expressions with conditional branching.

4. Correctness and fault tolerance requirements.

* Program first is correct, followed by grace.

* A new error may be generated when an error is changed, so consider the impact on other programs first before modifying.

* For all user input, the legality check must be carried out.

* Do not compare the equality of floating-point numbers. Such as:

10.0*0.1==1.0

5. Reusable Row requirements

* Repeated use of the algorithm or code to complete the relatively independent function should be abstracted as a common control or class.

* Common controls or classes should consider object-oriented thinking, reduce external contact, consider independence or encapsulation


Above said so many rules and regulations, a bit tired, then the following is close to the code to explain it.


(1) Specify the final modifier of the class as much as possible. A class with a final modifier is non-derived, that is, cannot be inherited

。 The Java compiler will look for opportunities to inline all final methods. This will increase the performance by an average of 50%.


(2) Reuse objects as much as possible. In particular, the use of String objects, when strings are concatenated, apply StringBuffer instead.


(3) Try to use local variables. Parameters that are passed when the method is called and temporary variables created in the call are saved in the stack and are easy to access. Other variables, such as static variables, are created at the end of the process and are accessed more slowly.


(4) In the development of Java+oracle's application system, the SQL statements embedded in Java should use uppercase as much as possible to alleviate the parsing burden of Oracle parser.


(5) In the Java programming process, the database connection, I/O flow operation must be careful, after the use is complete, close in time to release resources.


(6) The GC mechanism of the JVM. The JVM recycles garbage: objects are no longer referenced; however, the JVM's G is not a very mechanism, and even if the object satisfies the garbage collection conditions, it does not necessarily have to be immediately recycled. Therefore, it is recommended that you manually set the object to null after you have finished using it.


(7) When using the synchronization mechanism, try to use method synchronization instead of code block synchronization.


(8) Minimizing the repetition of variables.

Gca

for (int i = 0; i < list.size (); i++) {}

Should be replaced by:

for (int i = 0, size = list.size (); i < size; i++) {}
(9) Try to use lazy loading (delayed load) strategy, when needed to start the creation.

Gca

String str = "1111"; if (i = = 1) {list.add (str);}
Should be replaced by:

if (i = = 1) {String str = "1111"; List.add (str);}

(10) Do not use the Try/catch statement in the loop, it should be placed at the outermost layer.


(11) Initialize the StringBuffer with a suitable capacity value. When you use the default constructor to create a StringBuffer object, the capacity of StringBuffer is initialized to ask you 16 characters. When the stringbuffer reaches its maximum value, it increases its capacity to twice times the current two. Because the string reaches its maximum capacity, it must create a new character array, copying the original characters once to the newly created character array.


(12) Reasonably use Java class Java.util.Vector.

Because there is no "gap" between the elements in the vector. Removing any element other than the last element causes the element to move forward after the element is deleted.

Shown

for (int i = 0; i < 10000; i++) {v.remove (0);}

The code above is much slower than the code below.

for (int i = 0; i < 10000; i++) {V.remove (V.size ()-1);}
The best way to remove all elements from an object of type vector:

V.removeallelements ();
The following is a vector class object V contains the string "123456", the "123456" to delete the operation.

Shown

String s = "123456"; int i = V.indexof (s); if (i! =-1) {v.remove (s);}
This code is bad for performance because the IndexOf () method performs a sequential search for V, and the Remove () method also performs a sequential search.

After improvement:

String s = "123456"; int i = V.indexof (s); if (i! =-1) {v.remove (i);}
The improved code avoids a second search. The Remove () method gives the exact index position of the element to be deleted.

The best implementation of this feature:

String s = "123456"; V.remove (s);
with respect to the size () method, above (8) illustrates the use of the method, as to why, give the following code:

If size =100000for (int i =0;i<v.size (); i++) {}
because there are 100,000 elements in size (), the size is recalculated after each loop, so it is called 100,000 Times v.size ().


(13) When copying large amounts of data, use the

System.arraycopy ();


(14) Create an instance of the class without the new keyword.

When you create an instance of a class with the new keyword, all constructors in the constructor chain are automatically called. But if an object implements the Cloneable interface, we can call its clone () method. The Clone () method does not call any class constructors.

When using design mode, it is very simple to create a new object instance using the Clone () method if the object is created in Factory mode. For example, the following is a typical implementation of the factory pattern.

public static Test Getnewtest () {return new test ();

use the Clone () method:

private static test test = new Test ();p ublic static Test Getnewtest () throws Clonenotsupportedexception{return (test) test . Clone ();


(15) multiplication and division. Replacing multiplication with shift operations can greatly improve performance.

Shown

for (int i = 0; i < 100000; i+=5) {a = i * 8;b = i * 2;}
After modification:

for (int i = 0; i < 100000; i+=5) {a = i <<3;b = i <<1;}
Each left shift is equal to 1 bits multiplied by 2, and the 1 bits per right shift are equivalent to divided by 2.


(16) Do not declare the array: public static final


(17) Try to use HashMap and ArrayList, unless necessary, it is not recommended to use Hashtable and vectors, the latter due to the use of synchronization mechanism, resulting in performance overhead.


This blog post is nearing the end. Finally, the optimization of Java code in Android development.

In Android development, avoid using the internal get, set method as much as possible.

In Android programming, calls to virtual methods incur a lot of cost, more than instance property queries. We should use the get and set functions when calling externally, but we should call them directly when we call them internally.
























Code optimization: Learn Java and see Android

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.