83.JAVA programming Ideas-about Java performance

Source: Internet
Author: User
Tags string methods

83.JAVA programming Ideas-about Java performance

The Java language has a particular emphasis on accuracy, but reliable behavior is at the expense of performance. This feature is reflected in aspects such as automatic garbage collection, rigorous run-time checks, full bytecode checking, and conservative run-time synchronization. For an interpreted virtual machine, because there are a large number of platforms available to choose from, it further hinders performance.

"Finish it first, and then gradually improve." Fortunately, there are usually not too many places to improve. ”

1 Basic Methods

Only after the correct and complete detection of the program can we begin to address performance issues:

(1) Detect the performance of the program in the real environment. If the requirement is met, the target is met. If not, go to the next step.

(2) Find the most deadly performance bottlenecks. This may require a certain skill, but all efforts will not be wasted. If you simply guess where the bottleneck is and try to optimize it, it might be a white time.

(3) Use the speed-up technique described in this appendix and return to Step 1.

In order to make efforts not in vain, the positioning of the bottleneck is a crucial link. DONALDKNUTH[9] has improved a program that spends 50% of its time on about 4% of the amount of code. In just one working hour, he modifies a few lines of code to multiply the execution speed of the program. At this point, if the time to continue to invest in the remaining code changes, then it will only outweigh the gains. Knuth there is a famous saying in the programming world: "Premature optimization is the source of all Trouble" (Prematureoptimization is the root of all evil). The most sensible thing to do is to suppress the impulse of premature optimization, as doing so may omit many useful programming techniques, making the code more difficult to understand and manipulate, and require greater effort to maintain.

2 looking for bottlenecks

To identify the bottlenecks that most affect program performance, you can take the following methods:

2.1 Placement of your own test code

Insert the following "explicit" timing code to evaluate the program:

Long start = System.currenttimemillis ();

The arithmetic code to be timed is here.

Long time =system.currenttimemillis ()-Start;

Use SYSTEM.OUT.PRINTLN () to have a less commonly used method to print the cumulative time to the console window. Because the compiler ignores it when it goes wrong, it can be turned on or off with a static final Boolean, which allows the code to rest assured in the final release of the program, so that any time it is possible to take a contingency. Although more sophisticated evaluation methods can be used, it is undoubtedly the easiest way to measure the execution time of a particular task.

System.currenttimemillis () returns the time in 1 per thousand seconds (1 milliseconds). However, some systems have a time accuracy of less than 1 milliseconds (such as a Windows PC), so you need to repeat n times and then divide the total time by N to get accurate time.

2.2 J D K performance evaluation

The JDK package provides a built-in evaluation program that tracks the time spent on each routine and writes the results to a file. Unfortunately, the JDK evaluator is not stable. It works correctly in JDK 1.1.1, but is very unstable in later versions. To run the evaluator, add the-PROF option when invoking the non-optimized version of the Java interpreter. For example:

Java_g-prof MyClass

or add a program piece (applet):

680

Java_g-profsun.applet.appletviewer applet.html

It is not easy to understand the output information of the evaluation program. In fact, in JDK1.0, it actually truncated the method name to 30 characters. Therefore, some methods may not be distinguished. However, if your platform does support the-PROF option, try the "Hyperporf" [3] or Gregwhite "Profileviewer" of the Vladimir Bulatov to explain the results.

3 Special Tools

If you want to keep up with the trend of performance optimization tools, the best way is to make some Web site regulars. For example, "Tools for optimizing Java" (Java Optimizer) Web site made by Jonathan Hardwick:

4 Techniques for performance evaluation

_ Because the system clock is used in the evaluation, do not run any other processes or applications at that time, so as not to affect the test results.

_ If you modify your own program and try to improve its performance (at least on the development platform), test the execution time of the code separately before and after the modification.

_ Try to test every time in a fully consistent environment.

_ If possible, you should design a test that does not rely on any user input, to avoid the user's different reactions leading to errors in the results.

5 Speed -up method

Now, the key performance bottlenecks should be isolated. Next, you can apply two types of optimizations to it: the general approach and the Java-dependent language.

6 Conventional means

In general, an effective speed-up method is to redefine the program in a more realistic way. For example, in the book "Programming Pearls" (programming pick-up) [14],bentley uses a novel data description, it can generate very fast and very concise spelling checker, thus introducing Doug McIlroy's expression of English language. In addition, better algorithms may lead to greater performance gains than other methods-especially when the size of the dataset is getting bigger.

7 Language-dependent methods

For objective analysis, it is better to have a clear grasp of the execution time of various operations. In this way, the resulting result can be independent of the computer currently in use-by dividing the time spent on local assignment, and finally getting the "Standard Time".

Calculation Example Standard Time

Local assignment i=n; 1.0

instance assignment value This.i=n; 1.2

int value Added i++; 1.5

Byte value-added b++; 2.0

Short value-added s++; 2.0

Float value-added f++; 2.0

Double increment d++; 2.0

Empty loop while (true) n++; 2.0

Ternary expression (x<0)?-x:x2.2

Arithmetic call Math.Abs (x); 2.5

Array assignment A[0] = n; 2.7

Long value-added l++; 3.5

Method call Funct (); 5.9

Throw or catch exception try{throw e;} or catch (e) {}320

Synchronous method call Synchmehod (); 570

Creates a new object (). 980

Create new array new INT[10]; 3100

New objects and arrays can cause the heaviest overhead, and synchronization can be costly, and a step-by-way call can cause modest overhead.

8 Special Cases

String overhead: String Join operator + looks simple, but actually consumes a lot of system resources. The compiler can connect strings efficiently, but variable strings require considerable processor time. For example, suppose S and T are string variables:

System.out.println ("heading" + S + "trailer" + t);

The above statement requires creating a new StringBuffer (string buffer), appending an argument, and then converting the result back to a string with ToString (). As a result, both disk space and processor time can be severely consumed. If you are going to append multiple strings, consider using a string buffer directly-especially if you can reuse it in a loop. By preventing the creation of a new string buffer in each loop, you can save 980 units of object create time (as described earlier). With substring () and other string methods, performance can be further improved. If feasible, the character array can be even faster. Also note that due to the synchronization of the relationship, so StringTokenizer will cause a large overhead.

Synchronization: In the JDK interpreter, calling a synchronous method is typically 10 times times slower than calling an unsynchronized method. When processed by the JIT compiler, this performance gap increases to 50 to 100 times times (note that the previous table summarizes the time shown to be 97 times times slower). Therefore, to avoid using the synchronous method as much as possible-if not avoided, the synchronization of the method is slightly faster than the code block synchronization.

Reusing objects: It takes a long time to create a new object (according to the time summarized in the preceding table, the new time of the object is 980 times times the assignment time, and the time to create a new decimal group is 3,100 times times the value of the assignment). Therefore, it is wise to save and update the fields of old objects instead of creating a new object. For example, do not create a new Font object in your own paint () method. Instead, it should be declared as an instance object and then initialized once. After that, you can update it whenever you need it in paint (). See "Programming Pick-up" by Bentley

Exception: The exception handling module should only be discarded if it is not normal. What's called "abnormal"? This usually means that the program is experiencing problems, which is generally not desired, so performance is no longer a priority. When optimized, the small "try-catch" blocks are merged together. Because these blocks divide the code into small, separate pieces, it prevents the compiler from optimizing. On the other hand, excessive enthusiasm for removing the exception handling module can also lead to a decrease in the robustness of the code.

Hashing: First, the standard "hash list" (Hashtable) classes in Java 1.0 and 1.1 require styling and the simultaneous processing of system resources (570 units of assignment time) that is particularly consumed. Second, the early JDK libraries do not automatically determine the optimal table size. Finally, the hash function should be designed for the characteristics of the actual use item (key). For all these reasons, we can specifically design a hash class to work with a particular application to improve the performance of the regular hash table. Note that the hash mapping (HASHMAP) for the Java 1.2 collection is more flexible and does not automatically synchronize.

Method Inline: The Java compiler can embed this method only if the method belongs to final (final), Private (private), or static. And in some cases, it is also required that it should never have local variables. If your code spends a lot of time calling a method that doesn't contain any of these properties, consider writing a "final" version for it.

I/O: buffers should be used whenever possible. Otherwise, it might end up being a single byte of input/output at a time. Note that JDK 1.0 's I/O classes take a lot of synchronization, so if you use a "high-volume" Call Like Readfully () and then interpret the data yourself, you get better performance. Also note that the "reader" and "writer" classes in Java 1.1 have been optimized for performance.

Styling and Examples: styling consumes 2 to 200 units of assignment time. More expensive or even requires an upstream inheritance (genetic) structure. Other high-cost operations can damage and restore the ability to lower structures.

Graphics: The use of cutting technology to reduce the workload in the repaint (), multiply the buffer, improve the reception speed, while using the graphics compression technology, shorten the download time. The "Java Applets" from Javaworld and the "performing Animation" from Sun are two great tutorials. Please remember to use the most appropriate command. For example, to draw a polygon based on a series of points, DrawPolygon () is much faster than drawline (). If you must draw a straight line with a single pixel weight, drawLine (x,y,x,y) is faster than FillRect (x,y,1,1).

Use the API classes: try to use classes from the Java API as they are optimized for machine performance. This is difficult to achieve with Java. For example, when copying an array of any length, arrarycopy () is much faster than using loops.

Replace API classes: Sometimes the API class provides more functionality than we want, and the corresponding execution time increases. Therefore, a special version can be customized to allow it to do fewer things, but can run faster. For example, suppose an application needs a container to hold a large number of arrays. To speed up execution, you can replace the original vector (vector) with a faster array of dynamic objects.

1. Other recommendations

Move the repeating constant calculation out of the critical loop-for example, to calculate the buffer.length of a fixed-length buffer.

The static final (static end) constant helps the compiler to optimize the program.

Implement a fixed-length loop.

Use the Javac optimization option:-O. It optimizes compiled code by embedding static,final and private methods. Note that the length of the class may increase (only for JDK 1.1-earlier versions may not be able to perform byte verification). The new "Just-intime" (JIT) compiler dynamically accelerates the code.

Reduce the count to 0--as much as possible this uses a special JVM byte code.

83.JAVA Programming Ideas-about Java performance

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.