Some of the places in Java programming that "for performance" try to do

Source: Internet
Author: User
Tags stack trace wrapper

For the machine memory is full, in addition to new machine memory, but also should be well review our code, there are many code to write too casually, these bad habits or the language of the program is not understood to be a good suppression of repression.


Here are some of the things you can do in Java programming as a summary of the reference network resources.

1. Try to use a single case in the appropriate situation

Using a single example can reduce the load burden, shorten the loading time, improve the efficiency of loading, but not all places are applicable to a single case, simply speaking, the single case is mainly applicable to the following three aspects:

First, control the use of resources, through thread synchronization to control the concurrent access of resources;

Second, to control the production of instances in order to achieve the purpose of saving resources;

Third, control data sharing and allow multiple unrelated processes or threads to communicate without establishing a direct association.

2. Try to avoid using static variables arbitrarily

You know, when an object is defined as being referenced by a STATAIC variable, the GC typically does not reclaim the memory that the object occupies, such as Java code

    1. Public class a{

    2. Static b b = new b ();

    3. }

At this point, the lifetime of static variable B is synchronized with Class A, and if Class A does not unload, the B object will reside in memory until the program terminates.

3. Try to avoid too often creating Java objects


Try to avoid the frequently called methods, loops in the new object, because the system not only takes time to create objects, but also takes time to garbage collection and processing of these objects, in the scope of our control, to maximize the reuse of objects, it is best to use basic data types or arrays to replace the object.


4. Use the final modifier as much as possible

A class with a final modifier is not derived. In the Java Core API, there are many examples of final applications, such as java.lang.String. Specifying final for the string class prevents the consumer from overwriting the length () method. In addition, if a class is final, all methods of that class are final. The Java compiler looks for the opportunity Inline (inline) for all final methods (this is related to the specific compiler implementation). This will increase the performance by an average of 50%.

5. Use local variables as much as possible


The parameters passed when the method is called and the temporary variables created in the call are saved in the stack, which is faster. Other variables, such as static variables, instance variables, and so on, are created in the heap and are slower.

6. Try to handle the use of both the packing type and the basic type

Although wrapper types and basic types can be converted to each other during use, they produce a completely different area of memory, with basic type data generation and processing in the stack, the wrapper type being the object, and the instance being generated in the heap.

In the collection class object, there are objects that require processing for the wrapper type, and other processing advocates the use of basic types.


7. Use synchronized carefully to minimize the Synchronize method

All know that the implementation of synchronization is a great cost of overhead, and may even lead to deadlock, so try to avoid unnecessary synchronization control. When the Synchronize method is called, it locks the current object directly, and other threads cannot invoke the other methods of the current object until the method finishes executing. So the method of synchronize is as small as possible, and should try to use method synchronization instead of code block synchronization.

8. Use StringBuilder and StringBuffer for string connections whenever possible

That's not much to say.

9. Try not to use the Finalize method

In fact, it is very bad choice to put the resource cleanup in the Finalize method, because the GC workload is very large, especially when recovering Young's memory, most of which will cause the application to pause, so the choice of using the Finalize method for resource cleanup will lead to greater GC burden, Programs run less efficiently.


10. Try to use basic data types instead of objects

String str = "Hello";

In this way, a "hello" string is created, and the character cache pool of the JVM also caches the string;

String str = new string ("Hello");

At this point the program, in addition to creating a string, str refers to the bottom of the string object also contains a char[] array, the char[] array is stored in turn h,e,l,l,o


11. Single thread should try to use HashMap, ArrayList

HashTable, vectors, etc. use the synchronization mechanism to reduce the performance.


12. Create HashMap as reasonable as possible

When you want to create a larger hashmap, take advantage of another constructor

Public HashMap (int initialcapacity, float loadfactor)

Avoid HashMap multiple hash refactoring, the expansion is a very cost-performance thing, in the default initialcapacity only 16, and Loadfactor is 0.75, how much capacity you need, you'd better be able to accurately estimate the best size you need, The same is true of the same hashtable,vectors.


13. Minimize the repeated calculation of variables

Such as

for (int i=0;i<list.size (); i++)//should be changed to for (int i=0,len=list.size (); i<len;i++)

And in the loop should avoid the use of complex expressions, in the loop, the loop condition will be repeated calculation, if you do not use complex expressions, and the loop condition value is not changed, the program will run faster.


14. Try to avoid unnecessary creation

Such as

A = new A (); if (i==1) {list.add (a);}    Should be changed to if (I==1) {A A = new A (); List.add (a);}


15. Dispose of resources in the finally block as much as possible

The resources used in the program should be freed to avoid resource leaks. This is best done in the finally block. The finally block is always executed, regardless of the result of the program execution, to ensure that the resource is closed correctly.


16. Try to replace the ' A/b ' operation with a shift

"/" is a costly operation that uses shifting operations to be faster and more efficient

Such as

int num = A/4;int num = a/8;//should be changed to int num = a >> 2;int num = a >> 3;

Note, however, that the shift should be annotated because the shift operation is not intuitive and more difficult to understand


17. Try to use shift instead of ' a*b ' operation

Similarly, for the ' * ' operation, using the shift operation will be faster and more efficient

Such as

int num = A * 4;int num = A * 8;//should be changed to int num = a << 2;int num = a << 3;


18. Try to determine the capacity of the StringBuffer

The StringBuffer constructor creates an array of characters with a default size (usually 16). In use, if this size is exceeded, the memory is redistributed, a larger array is created, the original array is copied, and the old array is discarded. In most cases, you can specify the size when creating the StringBuffer, which avoids auto-growth when the capacity is insufficient to improve performance.

such as: stringbuffer buffer = new StringBuffer (1000);


19. Release references to useless objects as early as possible

Most of the time, the object referenced by the method local reference variable becomes garbage as the method ends, so most of the time the program does not have to explicitly set the local, reference variable to NULL.

For example:

Java code

    1. Public void Test () {

    2. Object obj = New object ();

    3. ......

    4. obj=null;

    5. }

The above is not necessary, and as the execution of the method test () is completed, the scope of the OBJ reference variable in the program ends. But if it's changed to the following:

Java code

  1. Public void Test () {

  2. Object obj = New object ();

  3. ......

  4. obj=null;

  5. //Execution time consuming memory operation, or call time consuming memory

  6. ......

  7. }

At this point it is necessary to assign the OBJ value to null to release the reference to the object as soon as possible.


20. Try to avoid using two-dimensional arrays

Two-dimensional data occupy more memory space than one-dimensional array, about 10 times times more.


21. Try to avoid using split

Unless it is necessary to avoid using split,split because it supports regular expressions, it is less efficient, and if it is frequent dozens of, millions of of calls will be resource intensive, and if you do need to call split frequently, Consider using Apache's Stringutils.split (String,char), which can cache results with frequent split.


ArrayList & LinkedList

One is a linear table, one is a list, a sentence, random query as far as possible to use arraylist,arraylist better than linkedlist,linkedlist also move the pointer, add the deletion of the operation LinkedList better than ArrayList, ArrayList also want to move the data, but this is a theoretical analysis, it is not necessarily the case, it is important to understand the 2 data structure, the right remedy.


23. Use System.arraycopy () as much as possible instead of iterating through the array

System.arraycopy () is much faster than copying an array by looping


24. Try to cache frequently used objects

As much as possible to cache objects that are used frequently, you can use arrays, or hashmap containers for caching, but this can cause the system to consume too much cache and degrade performance, and it is recommended to use some third-party open source tools such as Ehcache,oscache for caching. They basically implement a cache algorithm such as Fifo/flu.


25. Try to avoid very large memory allocations

Sometimes the problem is not caused by the heap state at the time, but by the failure of the allocation. The allocated memory blocks must be contiguous, and as the heap becomes more and more full, it becomes increasingly difficult to find larger contiguous blocks.


26. Caution With exceptions

When creating an exception, you need to collect a stack track, a stack trace that describes where the exception was created. Building these stack traces requires a snapshot of the runtime stack, which is a very expensive part. When you need to create a Exception, the JVM has to say: Don't move, I want to save a snapshot of what you are now, so stop the stack and the stack operation temporarily. Stack traces contain not only one or two elements in the runtime stack, but each element in the stack.

If you create a Exception, you have to pay the price. Fortunately, the overhead of catching exceptions is small, so you can use Try-catch to wrap the core content together. Technically, you can even throw an exception at random without a big cost. It is not a throw operation that incurs a performance penalty-although it is somewhat unusual to throw an exception without pre-creating an exception. The real cost is to create the exception. Fortunately, good programming habits have taught us that you should not throw an exception 3,721 or so. Exceptions are designed for exceptional situations and should be kept in mind when used.


Related reply:

Xuanyuan wrote

7. Use synchronized carefully to minimize the Synchronize method
Re: agree, but there is a place in the text is wrong, the use of the Synchronized keyword is not necessarily locked in the current object, to see the specific lock is what. If the synchronized is added to the method, it is locked with the object itself, and if it is a static method, the granularity of the lock is the class.
---------------
9. Try not to use the Finalize method
Re: Yes, the fundamental reason for not recommending a Finalize method is that the JVM's specification does not guarantee when the method is executed, so it is inappropriate to use this method to release resources, potentially causing long-time resources to be freed.
---------------
16. Use shift instead of ' A/b ' operation, 17. Use shift instead of ' a*b ' operation as far as possible.
Re: Individuals don't quite agree with these two articles. This does have better performance, but at the expense of readability. These two operators are not intuitive to many programmers. I think it's a good choice to sacrifice some performance for better readability and maintainability in a situation where hardware prices are not so expensive today.


Wuzhengju wrote

19. Release references to useless objects as early as possible
Most of the time, the object referenced by the method local reference variable becomes garbage as the method ends, so most of the time the program does not have to explicitly set the local, reference variable to NULL.
For example:

public void Test () {Object obj = new Object ();//... Obj=null; }


The above is not necessary, and as the execution of the method test () is completed, the scope of the OBJ reference variable in the program ends. But if it's changed to the following:

public void Test () {Object obj = new Object ();//... Obj=null;

Execute time-consuming, memory-intensive operations, or call time-consuming, memory-intensive methods
......
}
If object obj = new Object (); If this object is not a large object, is this necessary? Obj=null; just tell the JVM that this object has become garbage, as for when to recycle, not sure! This readability is not good!

This article is from the "beautiful Dē‖java Question" blog, please be sure to keep this source http://teny32.blog.51cto.com/8027509/1663080

Some of the places in Java programming that "for performance" try to do

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.