Android Application Development and Improvement series (2) -- Reading Notes of Practical Java Chinese edition (II)

Source: Internet
Author: User

Statement

You are welcome to repost, but please keep the original source of the article :)

Blog: http://www.cnblogs.com

Farmer's uncle: http://over140.cnblogs.com

 

Series

Android Application Development and Improvement series (1) -- Reading Notes of Practical Java Chinese edition (I)

 

Body

Note: entries and terms may differ from those in books, but try to keep them as they are and add your own understanding.

I. Performance

1. Focus on design, data structures, and algorithms.

Note: good design and wise selection of data structures and algorithms may be more important than efficient code.

 

2. Do not rely on Compiler Optimization Technology

 

3. Understand runtime code optimization

Note: JIT converts bytecode to a local binary code at runtime to improve performance. Therefore, the more times the code is executed after compilation, the more cost-effective the local code generation cost.

 

4. Using StringBuffer to connect strings is faster than that of strings, especially when many strings are concatenated.

 

5. Minimize object creation costs

Note: reuse existing objects. do not create unnecessary objects. Create them only when necessary.

 

6. Minimize synchronization

Note: If the synchronized function throws an exception, the lock is automatically released before the exception leaves the function. If the entire function needs to be synchronized, in order to generate small and fast code, use the function modifier first, instead of using the synchronized code block in the function.

 

7. Use stack variables whenever possible

Note: If the function frequently accesses member variables and static variables, you can use the local variable instead. After the operation, assign the value to the member/static variables.

 

8. Try to use static, final, and private functions

Note: such functions can be statically resolved (statically resolved) during compilation without the need for dynamic resolution (dynamic resolved ). (Subclass cannot be overwritten)

 

9. The member variables and static variables of the class have default values and must be reinitialized.

Note: Remember, there are no default values for local variables (for example, variables defined in the function ).

 

10. Use Basic data types as much as possible

Note: such as int, short, char, and boolean make the code faster and smaller.

 

11. Do not use the Enumeration and Iterator to traverse the Vector.

Note: Use for loop + get ()

 

12. Use System. arraycopy () to copy Arrays

Note: Use System. arraycopy () instead of for loop to generate faster code. For example:

Public void copyArray (int [] src, int [] dest ){
Int size = src. length;
System. arraycopy (src, 0, dest, 0, size );
}

System. arraycopy () is implemented by native method. It can directly and efficiently move the original array to the target array, so it runs faster.

 

13. The array is used first before Vector and ArrayList are considered. Reason:

A). The get () of the Vector is synchronized.

B). ArrayList is basically a non-thread synchronized Vector, which is faster than the Vector.

C) to add or remove elements in ArrayList and Vector, You need to reorganize the array.

Note: you do not need to use Vector or ArrayList unless you have an indefinite number of data to store. You can consider creating an array that is large enough, which may waste memory, but the performance gains may exceed the memory cost.

 

14. Manual code optimization

A) Remove blank functions and useless code.

B). Cut the intensity

Note: replace expensive operations with more efficient operations. A common optimization method is to use the duplicate copy operator (such as + =,-= ).

C). Merge Constants

Note: declare the variable as final so that the operation can be performed in the compiler.

D). Delete the same subexpression.

Note: A temporary variable can be used to replace repeated expressions.

E). Expand the loop

Note: If the number of cycles is small and the number of cycles is known, you can remove the loop structure and directly access the array elements. The disadvantage is that more code is generated.

F). Simplified Algebra

Note: use mathematical skills to simplify expressions. (For example, from 1 +... + 100)

G). The non-variant type in the moving cycle

Note: Non-changing expressions in a loop can be moved out of the loop without repeated expressions.

 

15. Compile as local code

Note: compile a part of the program into a local binary code and then access it through JNI.

 

Ii. Multithreading

1. For instance functions, the synchronization mechanism locks objects instead of functions and code blocks.

Note: The declaration of a function or code block as synchronized does not mean that it can only be executed by one thread at the same time (calls from different threads of the same object will be blocked ). Java cannot declare constructor as synchronized.

 

2. the locks for synchronizing Instance functions and static functions are different.

Note: Both are non-multithreading and secure. You can use instance variables for synchronization control, such as (byte [] lock = new byte [0]), which is more economical than any other object.

 

3. The data that can be modified in the synchronized function should be made private and the access function should be provided as needed. If the function returns a mutable object, you can clone the object first.

 

4. Avoid unnecessary Synchronization Control

Note: excessive synchronization control may cause code deadlocks or slow execution. Again, when a function is declared as synchronized, the lock obtained is the object that calls this function.

 

5. Use synchronized or volatile to access Shared variables.

NOTE: If concurrency is important and many variables do not need to be updated, you can consider using volatile. Once variables are declared as volatile, they are consistent with the primary memory each time they are accessed. If synchronized is used, it is consistent only when the lock is obtained and the lock is released.

 

6. Lock all objects used in a single operation

Note: If a synchronous function calls a non-synchronous instance function to modify an object, it is thread-safe. When using synchronization control, remember what synchronized does. It locks objects rather than functions or code.

 

7. Obtain multiple locks in a fixed and global order to avoid deadlocks. P/181 ~ P/185

Note: embedding the [lock sequence] requires additional work, memory, and execution time.

 

8. Use policyall () instead of policy ()

Note: Y () and policyall () are used to wake up the thread in the waiting state. waite () enables the thread to enter the waiting state. Notify () Only wakes up one thread.

 

9. Apply the rotation lock (spin locks) for wait () and policyall)

Note: The spin-lock pattern mode is simple and inexpensive, and ensures that the code waiting for a condition variable can follow the rules.

 

10. Use wait () and policyall () instead of polling loops)

Note: When wait () is called, the synchronization object lock is released and the thread is suspended (suspended, suspend. The paused thread does not occupy the CPU time until it is awakened. For example:

Public void run ()
{
Int data;
While (true ){
Synchronized (pipe ){
While (data = pipe. getDate () = 0 ){
Try {
Pipe. waite ();
}
Catch (InterruptedException e ){}
}
}

// Process Data
}
}

 

11. Do not assign a value to the object reference of the locked object.

 

12. Do not call stop () and suspend ()

Note: When stop () is used to stop a thread, all locks held by the thread are released, which may disturb internal data. suspend () is used to suspend a thread temporarily, however, locks held by them will not be released, which may lead to the risk of deadlock. Both of them will lead to unpredictable behavior and incorrect behavior.

When the thread's run () ends, the thread stops running. You can use round robin and variable control. The following code:

Private volatile boolean stop;

Public void stopThread ()
{
Stop = true;
}

Public void run ()
{
While (! Stop ){
// Process Data
}
}

Note: The keyword volatile is used here. Because Java allows a thread to keep a copy of the main memory variable in its private dedicated memory (which can be optimized), thread 1 calls stopThread () on thread 2 (), however, thread 2 may not immediately notice that the stop main memory variable has changed, resulting in failure to stop the thread in time.

 

Iii. Classes and interfaces

1. When implementing a final class (immutable class), follow the following rules:

A) declare that all data is private

B). Only the value function (getter) is provided, and the value assignment function (setter) is not provided)

C). Set instance data in the constructor.

D) if the function returns and accepts the reference final object, clone the object.

E). The differences between the application scenarios of the shallow copy and the deep copy. For example, deep copy is required to copy a Vector.

 

2. When implementing clone (), remember to call super. clone ()

Note: super. clone () must be called for both shallow and deep copies ().

 

3. Do not rely solely on finalize () to clear resources other than memory

Note: The finalize () function is called only before the Garbage Collector releases the space occupied by objects. During the collection, not all objects meeting the collection conditions are recycled, it cannot guarantee whether or not the API is called or when it is called. When implementing the finalize () method, remember to call super. finalize ().

 

4. Avoid calling non-final functions in the constructor to avoid overwriting and changing the original intention.

 

End

I borrowed books from my friends. I got my hand for a while. I had to read dozens of pages for a long time, and the rest of the books were only 3-5 days from my previous article to this article. I found that reading books in this way is good. On the one hand, it can speed up reading books. On the one hand, it is very suitable for me to write articles carefully and read and share the book reading records.

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.