Java's performance

Source: Internet
Author: User
Tags arrays constant exception handling hash inheritance integer string methods versions

"This appendix has been submitted by Joe Sharp and has been reproduced here with his consent." Please contact SharpJoe@aol.com "

The Java language specifically emphasizes accuracy, but reliable behavior is at the expense of performance. This feature is reflected in the automatic collection of garbage, strict run-time checks, complete bytecode checking, and conservative run-time synchronization, and so on. For an interpreted virtual machine, because there are a large number of platforms available for selection, it further hinders performance.
"Finish it first, then gradually perfect." Fortunately, there is usually not much room for improvement. "(Steve McConnell's about performance" [16])
The purpose of this appendix is to guide you in finding and optimizing the "part that needs to be perfected".

D.1 Basic Methods
Once you have correctly and completely tested your program, you can begin to address performance issues:
(1) Detect the performance of the program in the real environment. If meet the requirements, the goal is achieved. If it does not, go to the next step.
(2) Looking for the most lethal performance bottleneck. This may require some skill, but all efforts will not be in vain. Simply guessing where the bottleneck is and trying to optimize it may be a waste of time.
(3) Use the speed-increasing technology described in this appendix and return to Step 1.

In order to make efforts not to be wasted, the location of bottlenecks is a vital link. Donald Knuth[9] has improved a program that spends 50% of its time on about 4% of the code. In only one work hour, he modified a few lines of code, so that the execution speed of the program doubled. At this point, if you continue to devote time to the remaining code changes, it will only outweigh the gains. Knuth has a famous saying in programming: "Premature optimization is the root cause of all trouble" (premature optimization is the root of all evil). The wisest thing to do is to curb the urge to prematurely optimize, because doing so may omit a variety of useful programming techniques, making it more difficult to understand and manipulate, and require greater effort to maintain.

D.2 Looking for bottlenecks
To identify bottlenecks that most affect program performance, there are several ways to do this:

d.2.1 to install their own test code
Insert the following "explicit" timing code to evaluate the program:

Long start = System.currenttimemillis ();
The operation code to be timed is here.
Long time = System.currenttimemillis ()-Start;

Using System.out.println (), a method that is not commonly used to print cumulative time to the console window. As soon as an error occurs, the compiler ignores it, so you can use a "static final Boolean" (Static final Boolean) to turn on or off the timer, so that the code can rest assured in the final release of the program, so that any time you want to take the emergency. Although more sophisticated metrics can be used, this is the easiest way to measure the execution time of a particular task.
The time returned by System.currenttimemillis () is 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, then divide the total time by N to get the exact time.

d.2.2 JDK Performance evaluation [2]
The JDK kit provides a built-in evaluation program that tracks the time spent on each routine and writes the evaluation results to a file. Unfortunately, the JDK Profiler is not stable. It works in JDK 1.1.1, but it is very unstable in later versions.
To run the evaluation program, add the-PROF option when you invoke an optimized version of the Java interpreter. For example:
Java_g-prof MyClass
Or add a piece of program (applet):
Java_g-prof Sun.applet.AppletViewer applet.html
It is not easy to understand the output information of the evaluation program. In fact, in JDK 1.0, it actually truncated the method name to 30 characters. So you may not be able to distinguish some methods. However, if the platform you are using does support the-PROF option, try "Hyperporf" [3] or Greg White's "Profileviewer" in Bulatov to explain the results.

d.2.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 Optimization tool) Web site made by Jonathan Hardwick:
Http://www.cs.cmu.edu/~jch/java/tools.html

Skill of d.2.4 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 program and try to improve its performance (at least on the development platform), you should test the execution time of the code separately before and after the modification.
Try to test each time in a completely consistent environment.
If possible, design a test that does not rely on any user input to avoid the user's different reactions resulting in error.

The method of raising speed of D.3
The key performance bottlenecks should now be isolated. Next, you can apply two types of optimizations to it: the general approach and the dependency on the Java language.

d.3.1 Conventional means
In general, an effective speed-raising approach is to redefine the program in a more realistic way. For example, in the book Programming pearls, [14],bentley uses a description of the novel's data to produce a very fast and very compact spell checker that introduces Doug McIlroy's expression of the English language. In addition, better algorithms may lead to greater performance improvements than other methods-especially when the data sets are growing in size. For more information on these conventional tools, please refer to the "General books" list at the end of this appendix.

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

Operation Example Standard Time

Locally assigned value i=n; 1.0
An instance is assigned a 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 increment f++; 2.0
Double increment d++; 2.0
Empty loop while (true) n++; 2.0
Three-dimensional expression (x<0)-x:x 2.2
Arithmetic calls Math.Abs (x); 2.5
Array assignment A[0] = n; 2.7
Long value-added l++; 3.5
Method calls Funct (); 5.9
Throw or catch exception try{throw e;} or catch (e) {} 320
Synchronous method calls Synchmehod (); 570
Create new object (); 980
New array new INT[10]; 3100

Through their own systems (such as my Pentium Pro,netscape 3 and JDK 1.1.5), these relative times reveal that creating new objects and arrays can have the heaviest overhead, and that synchronization can cause heavy overhead, while a different-step method call can cause modest overhead. reference resources [5] and [6] have summed up the measurements with the web addresses of the programs, and can run them on their own machines.

1. General modifications
Here are some general recommendations for speeding up the execution of key parts of the Java program (note the test results before and after the change).

Will... To modify into ... Reason

Interface abstract class (only one parent) multiple inheritance of an interface can hinder performance optimization
Non-local or array loop variable local loop variable the time of the first instance integer assignment is 1.2 times times that of the local integer assignment time, based on the time-consuming comparison of the preceding table, but the time of the array assignment is 2.7 times times the value of the local integer assignment
Link list (fixed size) save discarded linked items, or replace the list with a loop array (roughly known) each new object is equivalent to a local assignment of 980 times. Refer to "Reusing Objects" (next section), Van wyk[12] p.87, and bentley[15] p.81
X/2 (or any power of 2) x>>2 (or any power of 2) uses faster hardware instructions

d.3.3 Special case
String Cost: String concatenation operator + seemingly simple, but the actual need to consume a lot of system resources. The compiler can efficiently connect strings, 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 a new StringBuffer (string buffer), appends the argument, and then converts the result back to a string with ToString (). As a result, both disk space and processor time can be severely depleted. If you are preparing to append multiple strings, consider using a string buffer directly-especially if you can reuse it in a loop. By preventing a new string buffer from being created in each loop, you can save 980 of units of object creation time (as described earlier). Using substring () and other string methods, you can further improve performance. If feasible, the speed of the character array can be even faster. Also note that because of the synchronization of the relationship, so StringTokenizer will cause a large cost.
Sync: In the JDK interpreter, calling a synchronization method is typically 10 times times slower than calling an unsynchronized method. This performance gap is raised to 50 to 100 times times after being processed by the JIT compiler (note that the previous table summarizes the time shown to be 97 times times slower). So avoid using the sync method as much as possible--if you can't avoid it, 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 (the object's new time is 980 times times that of the assignment time, based on the time summarized in the previous table, and the new decimal group is 3,100 times times the time of the assignment). Therefore, the most sensible thing to do is 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, declare it as an instance object and initialize it again. After that, updates can be made at any time when the paint () is needed. Refer to Bentley's "programming to pick up the shell", p.81[15].
Exception: The exception handling module should be discarded only if it is not normal. What is called "abnormal"? This usually means that the program encounters a problem that is generally not intended to be seen, 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, the compiler is prevented from optimizing. On the other hand, if you are too keen to remove the exception handling module, you may also cause code robustness to fall.
Hashing: First, the standard "hash" (Hashtable) classes for Java 1.0 and 1.1 require styling and a special consumption of synchronous processing of system resources (570-unit assignment time). Second, the early JDK library does not automatically determine the best table size. Finally, the hash function should be designed for the characteristics of the actual use item (key). For all of these reasons, we can specifically design a hash class that fits with a particular application to improve the performance of the regular hash table. Note that the hash map (HASHMAP) of the Java 1.2 Collection library has greater flexibility and does not automatically synchronize.
Method Inline: The Java compiler can embed this method only if the method is final (final), Private (private), or static. In some cases, it is also required that it must not have local variables. If your code spends a lot of time calling a method that does not contain any of these properties, consider writing a "final" version of it.
I/o: buffer should be used whenever possible. Otherwise, it may end up being the result of only one 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 Java 1.1 's "reader" and "writer" classes have been optimized for performance.
Modeling and Example: styling consumes 2 to 200 units of assigned time. More expensive even requires tracing the inheritance (genetic) structure. Other high cost operations can lose and restore the ability to lower structures.
Graphics: Reduce the amount of work in the repaint (), multiply the buffer, increase the receiving speed by using the shearing technology, and shorten the download time by using the graphic compression technology. The "Java Applets" from Javaworld and the "performing Animation" from Sun are two good tutorials. Please remember to use the most appropriate command. For example, to draw a polygon based on a series of points, the DrawPolygon () is much faster than the DrawLine (). If you have to draw a straight line with a single pixel thickness, drawLine (x,y,x,y) is faster than FillRect (x,y,1,1).
Use API classes: Use classes from the Java API as much as possible, because they are already optimized for machine performance. This is difficult to achieve in Java. For example, when copying an array of any length, arrarycopy () is much faster than using loops.
Replace API class: Sometimes the API class provides more functionality than we expect, 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 dynamic object array.

1. Other recommendations
Move the repeating constant calculation beyond the critical loop-for example, to compute the buffer.length of a fixed-length buffer.
The static final (static end) constant helps the compiler optimizer.
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 (for JDK 1.1 only – earlier versions may not be able to perform byte verification). The new "Just-in-time" (JIT) compiler dynamically accelerates the code.
Reduce the count to 0--as much as possible this uses a special JVM byte code.

D.4 Reference Resources

d.4.1 Performance Tools
[1] Microbenchmark running in Pentium Pro 200,netscape 3.0,jdk 1.1.4 (see Reference resources below [5])
[2] Sun's Java document page--jdk java interpreter theme:
Http://java.sun.com/products/JDK/tools/win32/java.html
[3] The hyperprof of Vladimir Bulatov
Http://www.physics.orst.edu/~bulatov/HyperProf
[4] Greg White's profileviewer
Http://www.inetmi.com/~gwhi/ProfileViewer/ProfileViewer.html

d.4.2 Web site
[5] The best online reference for the optimization theme of Java code is Jonathan Hardwick's "Java optimization" Web site:
Http://www.cs.cmu.edu/~jch/java/optimization.html
Java Optimization Tools Home page:
Http://www.cs.cmu.edu/~jch/java/tools.html
and "Java Microbenchmarks" (with a 45-second evaluation process):
Http://www.cs.cmu.edu/~jch/java/benchmarks.html

d.4.3 Articles
[6] "Make Java fast:optimize! How to get the greatest performanceout of the Your code through low-level optimizations in Java (make Java faster: Optimize!) How to make your code perform the most outstanding performance with low-level optimizations in Java. Author: Doug Bell. Url:
Http://www.javaworld.com/javaworld/jw-04-1997/jw-04-optimize.html
(includes a comprehensive performance evaluation program, with detailed comments)
[7] "Java Optimization resources" (Java Optimization Resource)
Http://www.cs.cmu.edu/~jch/java/resources.html
[8] "Optimizing Java for Speed" (optimize Java, improve speed):
Http://www.cs.cmu.edu/~jch/java/speed.html
[9] "an empirical Study of Fortran Programs" (Fortran program actual combat analysis). Author: Donald Knuth. Published in 1971. Volume 1th, p.105-33, "software-practice and practice".
[Ten] "Building high-performance applications and Servers in Java:an experiential". Author: Jimmy Nguyen,michael fraenkel,richardredpath,binh Q Nguyen and Sandeep K. Singhal. IBM t.j Watson researchcenter,ibm Software Solutions.
Http://www.ibm.com/java/education/javahipr.html

d.4.4 Java Professional Books
[11] "Advanced java,idioms,pitfalls,styles, and programming Tips". Author: Chris Laffra. Prentice Hall was published in 1997 (Java 1.0). 11th Chapter 20th subsection.

d.4.5 General Books
[12] Structures and C Programs (data structure and C program). Author: J.van Wyk. Addison-wesly published in 1998.
[13] "Writing Efficient Programs" (write a valid procedure). Author: Jon Bentley. Prentice Hall was published in 1982. Special Reference p.110 and p.145-151.
[14] "More Programming Pearls" (second edition of the program pick Beta). Author: Jonbentley. "Association for Computing Machinery", February 1998.
[15] "Programming Pearls" (Program picking Bay). Author: Jone Bentley. Addison-wesley published in 1989. The 2nd part highlights the general performance improvement issues. [16] Code COMPLETE:A Practical Handbook of Software Construction (complete code index: Practical Software Development Manual). Author: Steve McConnell. Microsoft Press published in 1993, 9th chapter.
[17] "Object-oriented system Development" (Development of object-oriented systems). Author: Champeaux,lea and Faure. 25th Chapter.
[18] The Art of programming (programming Arts). Author: Donald Knuth. Volume 1th "Basic algorithm 3rd Edition"; 3rd volume "Sort and search 2nd edition". Addison-wesley published. This is an encyclopedia of program algorithms.
[19] "algorithms in c:fundammentals,data Structures, sorting,searching" (C algorithm: Foundation, data structure, sorting, Search) 3rd edition. Author: Robertsedgewick. Addison-wesley published in 1997. The author is a student of Knuth. This is one of seven versions that are specifically discussed in several languages. The algorithm is explained in a simple and simple sense.

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.