Java Performance (Source: Java Programming Thoughts) This appendix is submitted by Joe Sharp. Java language emphasizes accuracy, but reliable behavior is at the price of performance. This feature is reflected in automatic collection of garbage, strict runtime test, complete In terms of bytecode check and conservative period synchronization. For an interpreted virtual machine, since there is currently a large number of platforms available, it is further hindered by performance. "After doing it, then gradually perfect. Fortunately, it is usually not too much place where it needs to be improved. "(Steve McConnell" About Performance "[16]) This appendix is to guide everyone to find and optimize" that is perfect ".
D.1 Basic method only After the program is properly and completely detected, the performance of performance: (1) Detecting the performance of the program in a realistic environment. If you meet the requirements, the target is achieved. If you do not meet, go to the next step. (2) Find the most deadly performance bottleneck. This may ask a certain skill, but all efforts will not be in a white fee. If you simplect the bottleneck, and try to optimize, it may be white flowers. (3) Use the speed of speed introduced in this appendix and return to step 1.
In order to make efforts not to be white, the positioning of the bottleneck is a crucial ring. Donald Knuth [9] has improved a program that spends 50% of the time to about 4% of the code. In just a working hour, he modified several lines of code to make the execution speed of the program. At this point, if the time continues to enter the residual code, it will only be lost. Knuth has a famous saying in the programming industry: "Premature Optimization Is The Root of All Evil). The most sensible approach is to suppress the impulse of premature optimization, because it can be missed a variety of useful programming technology, resulting in more difficult to understand and control, and more energy is maintained.
D.2 Looking for bottlenecks to find bottlenecks that most influencing program performance can take the following methods:
D.2.1 Inserting your test code inserts the "explicit" timing code to evaluate the program:
Long Start = system.currenttimemillis (); // The calculation code to be timed is LONG TIME = System.currentTimeMillis () - START;
Using System.out.Println (), a non-commonly used method prints the accumulated time to the console window. Because of an error, the compiler will ignore it, so you can use a "static final Boolean" (Static Final Boolean) to turn the code, so that the code can stay in the final release program, so you can take emergency . Although more complex evaluation means can also be selected, this is undoubtedly the easiest way for execution time for a measure of a specific task. System.currentTimeMillis () returned to one third of the second (1 millisecond). However, some systems have a time accuracy of less than 1 milliseconds (such as Windows PC), so it is necessary to repeat N times, and then divide the total time divided by N to obtain accurate time.
D.2.2 JDK Performance Evaluation [2] JDK supporting provides a built-in evaluation program that tracks the time spent on each routine and writes the evaluation result into a file. Unfortunately, the JDK evaluator is not stable. It works normally in JDK 1.1.1, but it is very unstable in subsequent versions. To run the evaluation program, add -PROF options when calling the unopened version of the Java interpreter. For example: java_g -prof myclass or plus a program (Applet): java_g -prof sun.applet.appletViewer Applet.html is not easy to understand the output information of the evaluation program. In fact, in JDK 1.0, it actually cuts the method named 30 characters. Therefore, some methods may not be distinguished. However, if you use the platform to support the -prof option, you can try the "HyperPorf" [3] or Greg White's "ProfileViewer" 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 sites. For example, "Tools for Optimizing Java" (Java Optimization Tools) made by Jonathan Hardwick: http://www.cs.cmu.edu/~jch/java/tools.html
D.2.4 Skills of Performance Evaluation ■ Due to the system clock due to evaluation, do not run any other processes or applications at that time to avoid affecting the test results. ■ If you have modified your own program, try (at least on the development platform) to improve its performance, then test the execution time of the code before and after the modification. ■ Try to perform each time test in a fully consistent environment. ■ If possible, you should design a test that does not rely on any user input, and avoids the result of the error.
D.3 Speed Methods Now, the key performance bottleneck should have been isolated. Next, two types of optimizations can be applied: routine means and dependent on Java languages.
D.3.1 General means typically, a valid speed method is to redefine the program in a more realistic way. For example, in "programing pearls" [14], Bentley takes advantage of a novel data description, it can generate a very fast, and very streamlined inspector, introduce Doug Mcilroy to English language Expression. In addition, better algorithms may bring greater performance improvement than other methods - especially when the size of the data set is getting bigger and bigger. For details of these routine means, please refer to the "General Book" list at the end of this appendix.
D.3.2 Dependency Language Method For objective analysis, it is best to clarify the implementation time of various operations. In this way, the resulting result can be independent of the currently used computer - the final result is "standard time" by dividing the time to assign a value in the local area.
Operation example standard time
Local assignment i = n; 1.0 instance assignment this.i = n; 1.2int value added i ; 1.5byte value added B ; 2.0Short value added S ; 2.0double value value F ; 2.0double value value D ; 2.0 empty cycle while (true) n ; 2.0 Trimer expression (x <0)? -X: x 2.2 arithmetic call math.abs (x); 2.5 array assignment a [0] = n; 2.7long value-added L ; 3.5 method call funct (); 5.9throw or catch Abnormal try {throw e;} or catch (e) {} 320 synchronization method calls synchmehod (); 570 new object new object (); 980 new array new int [10]; 3100 passed its own system (such as my Pentium 200) Pro, Netscape 3 and JDK 1.1.5), these relative time unveiled: New objects and arrays will cause the most heavy overhead, synchronization will cause more heavy overhead, and one-time method call will cause moderate overhead . Reference Resources [5] and [6] summarizes the web address of the measuring program, you can run them on your own machine.
1. General Modification The following is some of the regular operational recommendations that speeds up the Java program key section (note the test results before and after the modification).
Will modify ...
Interface Abstract Class (Multiple Inherions for Interfaces) The Multiple Inherions of Interfaces The Optimized Non-Local or Arrse Circulatory Variable Variable Variable Variables Depending on the time-consuming time of the previous table, the time of the instance integer assignment is 1.2 for local integers. 1.2 Femback, but the array assignment time is a 2.7-fold link list (fixed size) saved by local integer assignment, or replaces the list to a loop array (generally known size) Each object is applied, which is equivalent to local assignment 980 Time. Refer to "Reuse Object" (next section), VAN WYK [12] P.87 and Bentley [15] P.81X / 2 (or 2 of any power) X >> 2 (or 2) Using faster hardware instructions
D.3.3 Special circumstances ■ Strings overhead: String Connection Operator seems simple, but actually consumes a lot of system resources. The compiler can be efficiently connected to the string, but the variable strings require a considerable processor time. For example, suppose S and T are string variables: system.out.println ("Heading" S "Trailer" T); the above statement requires new StringBuffer, string buffer), adds arguments, then use toString ) Convert the result back to a string. Therefore, regardless of disk space or processor time, it will be severely consumed. If you are ready to add multiple strings, consider using a string buffer directly to use a string buffer, especially when you reuse it in a loop. By disable new string buffering in each cycle, save 980 units of object creation time (as mentioned above). The performance can be further improved by using subString () and other string methods. If it is feasible, the speed of the character array can even be faster. It is also necessary to pay attention to the relationship of synchronization, so StringTokenizer will cause greater overhead. ■ Synchronization: In the JDK interpreter, call synchronization methods typically be more slower than that of the call disagreement method. After the JIT compiler is processed, the gap in this performance is raised to 50 to 100 times (note that the previous table summary shows a slow 97 times). So avoid using synchronous methods as much as possible - if you don't avoid it, the synchronization of the method is slightly more faster than the synchronization of the code block. ■ Reuse using objects: Time to get a long time to create a new object (depending on the time summary, the new time of the object is 980 times the assignment time, and the time to create a decimal set is 3100 times). Therefore, the most sensible approach is to save and update the field of old objects, not to create a new object. For example, don't create a new Font object in your own Paint () method. Instead, it should be declared as an example object, and then initialize once. After this, you can update it at any time in Paint (). See "Programming Pickup" edited by Bentley, P.81 [15]. ■ Abnormal: The abnormal processing module should only be discarded in an abnormal case. What is it called "abnormal"? This usually refers to a problem, which is generally unwilling to see, so performance is no longer a priority. When optimizing, the small "try-catch" block is combined together. Since these blocks split the code into small, their independent fragments, it hinders the compiler to optimize. On the other hand, if the excessive is keen to delete an abnormal processing module, it may also cause a decline in code. -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------- ■ Hash: First, Java 1.0 and 1.1 Standard "HashTable" class requires shape and special consumption system resource synchronous processing (570 unit assignment time). Second, early JDK libraries cannot automatically determine the best form size. Finally, the hash function should be designed for the characteristics of the actual use item (Key).
Taking into account all these reasons, we can specifically design a hash class to cooperate with specific applications to improve the performance of conventional listings. Note that the HashMap of the Java 1.2 Collection Library has greater flexibility and will not automatically synchronize. ■ Method embedded: Only the Java compiler can embed this method in the case where the method belongs to Final (final), private (dedicated), or STATIC (static). Moreover, in some cases, it also requires it absolutely not a partial variable. If the code spent a lot of time calls a method that does not contain any of the above properties, consider writing a "final" version. ■ I / O: The buffer should be used as much as possible. Otherwise, it will ultimately only input / output a byte of evil. Note that the I / O class of JDK 1.0 uses a large number of synchronization measures, so if you use a "large amount" call like ReadFully (), you can get better performance by explaining data yourself. It is also important to note that the "Reader" and "Writer" classes of Java 1.1 have been optimized for performance. ■ Modeling and instance: Modeling will consume 2 to 200 assignment time. The overhead is even asked to inherit (genetically) structure. Other high-cost operations will lose and restore the ability to restore lower-layer structures. ■ Graphics: Use shear technology to reduce the workload in repaint (); multiplier buffer, improve the receiving speed; simultaneously use graphic compression technology to shorten the download time. "Java Applets" from JavaWorld and "Performing Animation" from Sun are two good tutorials. Please remember the use of the most appropriate command. For example, to draw a polygon in accordance with a series of points, DrawPolygon () is much faster than DrawLine (). If you have to draw a single pixel thick line, Drawline (X, Y, X, Y) speed is faster than FillRect (X, Y, 1, 1). ■ Use the API class: Try to use classes from Java API because they have been optimized for the performance of the machine. This is hard to achieve with Java. For example, when copying any length of array, ArraryCopy () is much more than the speed of using the cycle. ■ Replace the API class: Sometimes, the API class provides more than what we want more, and the corresponding execution time will increase. Therefore, you can customize special versions, let it do less, but you can run faster. For example, assume that an application requires a container to save a large number of arrays. To speed up the execution speed, the original Vector (vector) can be replaced with a faster dynamic object array.
1. Other recommendations ■ Calculate the repeated constant to the critical cycle - such as buffer.length of the fixed length buffer. ■ static final (Static Final) constant helps the compiler optimization program. ■ Implement a fixed length cycle. ■ Use Javac optimization options: -o. It optimizes compiled code through embedded Static, Final, and Private methods. Attention The length of the class may increase (only the earlier version may not perform byte check) on the JDK 1.1 - earlier version). The new "Just-In-Time" compiler will dynamically accelerate the code. ■ minus the count to 0 ~ This uses a special JVM byte code. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Java appears after the mid-nineties, while winning praise Also attracted some criticisms. Winner is mainly the Java's cross-platform operability, that is, the so-called "Write Once, Run Anywhere". However, due to the performance of Java, there is still a lot of gaps compared to the Running efficiency, there is a lot of gaps. criticism. For the application of the server, the performance problem of Java seems to be unclear, so that some Java technology, such as JSP, Servlet, EJB, etc. are very obvious, so that some JAVA technology, such as JSP, servlet, ejb, etc. Large application, but in fact, Java's performance issues still exists on the server. Below I will discuss the performance and implementation efficiency of Java and improve Java performance. One. About the basic knowledge of performance 1. The definition of performance we need to understand the true meaning of "performance" before we discuss how to improve Java performance. We generally define the following five aspects as the criteria for judging performance. 1) Performance of the calculation --- Which algorithm performs performance is preferably 2) The allocation of the memory ---- The program needs to be assigned how much memory, the efficiency and performance of the runtime. 3) Start time ---- How much time it takes to start. 4) The scalability of the program ----- the performance of the program in the case of user load. 5) Performance's understanding ------ How can users recognize the performance of the program. For different applications, the requirements for performance are also different. For example, most applications take longer time at startup, thereby decreasing the starting time; the application of the server is usually allocated with large memory space, so the requirements for memory are also reduced. However, this is not that the performance of the two aspects can be ignored. Second, the performance of the algorithm is very important for applications that use business logic to transactional operations. In general, the requirements for the application will determine the priority to each performance.
2. How to improve Java performance improve Java performance, generally considering the following four main aspects: (1) Method and mode of programming and model A good design can improve the performance of the program, not only for Java, but also any Programming language. Because it makes full use of various resources, such as memory, CPU, cache, object buffer pools and multithreades, thereby designing high performance and scalable systems. Of course, in order to improve the performance of the program, it is more difficult to change the original design, but the importance of program performance is often higher than the design of the design. Therefore, there should be a good design model and method before the programming begins. (2) Environment of Java deployment. The environment of Java deployment refers to techniques for explaining and executing Java bytecles, usually as follows. That interpretation INSTRUCTIONS (Interpreter Technology), Technical time compiler (Just In Time Compilier Technology), adaptive optimization technique (Adaptive Optimization Technology), dynamic optimization, machine code is compiled ahead technique (Dynamic Optimization, Ahead Of Time Technology) And compile as machine code. These technologies are generally optimized by optimizing thread models, adjusting the size of the stack and stack to optimize Java performance. When considering the improvement of Java performance, you must first find bottlenenecks that affect Java performance. After confirming the rationality of the design, the Java deployment environment should be adjusted to improve the performance of the Java application by changing some parameters. See Section 2 of the specific content. (3) The implementation of the Java application When discussing the performance issues of the application, most of the programmers will consider the code of the program, which is of course pair, when more important is to find bottleneck code affecting program performance. In order to find these bottleneck code, we generally use some auxiliary tools, such as JProbe, OptimizIT, VTune, and some analyzed tools such as Towerj Performance. These assisted tools can track the time consumed by each function or method in the application, thereby improving the performance of the program. (4) Hardware and operating systems In order to improve the performance of Java applications, use Fast CPUs and more memory, and believe that this is the only way to improve program performance, but this is not the case. Practical experience and facts have proven that only the application performance bottlenecks, there is appropriate way, such as design patterns, deployment, and operating system adjustments, is the most effective. 3. The usual performance bottleneck in the program. All applications have performance bottlenecks. In order to improve the performance of the application, it is necessary to reduce the bottleneck of the program as much as possible. The following is a performance bottleneck that often exists in the Java program.
[img] http://www.computerworld.com.cn/htm/app/aprog/01_7_9_3a.gif [/ img] After you understand these bottlenecks, you can reduce these bottlenecks, thereby improving Java applications. Performance 4. Increases the performance of Java Program Performance In order to improve the performance of the Java program, you need to follow six steps below. a) Clear specific requirements for performance Before implementing a project, you must clarify the specific requirements for program performance, such as this application to support 5000 concurrent users, and the response time is within 5 seconds. But it also understands that the requirements for performance should not conflict with other requirements of the program. b) Understanding the performance of the current program You should understand the performance of your application with the gap between the performance requirements of the project. The usual indicator is the number of processing and response time in unit time, and sometimes the utilization of CPU and memory is compared. c) Find the program's performance bottleneck in order to find out the performance bottleneck in the program, usually use some analytics tools, such as TowerJ Application Performance Analyzer or VTune to see and analyze the time consumption of each element in the program stack, thus finding and correcting A bottleneck code with reduced performance, thereby increasing the performance of the program. These tools can also find potential issues such as excessive abnormalities, garbage collection. d) Take appropriate measures to improve performance After the bottleneck code that causes the program performance, we can use the four aspects of the improvement performance, namely design mode, Java code implementation, deployment of Java's environment and Operating systems to improve the performance of the application. The details will be described in detail in the following. e) Improvement of amendments only to improve performance only one aspect that may cause performance reduction, and then the performance of the program is improved, and it should not change multiple aspects, because you will not know Which aspect change has improved the performance of the program, which is not, that is, the program bottleneck is not known. f) Return to step c, continue to work similar to the performance, which has been achieved. Two. When the Java deployment environment and compilation technology develops Java applications, first compile Java source programs as unrelated to the platform. These bytes can be performed by various JVM-based technologies. These technologies are mainly divided into two large categories. That is, a technique based on the interpretation and technique based on the pre-compiled as local code. The schematic is as follows: [IMG] http://www.computerworld.com.cn/htm/app/aprog/01_7_9_3b.gif [/ img] Specific class five categories: a) Interpretation of its structural map and The execution process is as follows:
[img] http://www.computerworld.com.cn/htm/app/aprog/01_7_9_3c.gif [/ img] Java compiler first compiles the Java source file as a bytecode. These bytes are the Java Virtual Machine (JVM) is the machine's instruction code. Then, Java's interpreter continuous loops takes out the bytecode and executes. The advantage of this is that the cross-platform of the Java language can be implemented, and the generated bytecode is also compacted. Some of Java, such as security, dynamics have to be kept; but the disadvantage is that the province's generated bytecode is not optimized, and the speed is slower than all compiled local code. b) Timely Compilation Technology (Just In Time) Timely Compilation Technology is to resolve the instruction interpretation technology is relatively low, and the speed is relatively slow, and the structural drawings are shown below.
[img] http://www.computerworld.com.cn/htm/app/aprog/01_7_9_3d.gif [/ img] Its main change is before the Java program is executed, and the JIT compiler compiles the Java's bytecode as Machine code. Thereby directly executing the machine code directly at runtime without using the bytecode. At the same time, the code also has been partially optimized. The advantage of this is that it greatly improves the performance of the Java program. At the same time, since the results of the compilation are not stored in the program running, the time to store the loader is also saved; the disadvantage is that the JIT compiler is optimized to all the code, so it is also a lot of time. IBM and Sun provide relevant JIT products. c) Adaptive Optimization Technology (Adaptive Optimization Technology) is not optimized for all bytecodes compared to JIT technology. It tracks the procedure of the program run, thus discovering the code that needs to be optimized, and dynamically optimized the code. For optimized code, take 80/20 strategies. In theory, the longer the program is running, the more optimized the code. The structural diagrams are as follows: [img] http://www.computerworld.com.cn/htm/app/aprog/01_7_9_3e.gif [/ img] It advantages It is that adaptive optimization technology makes full use of the information execution time, issue The program's performance bottleneck, thereby improving the performance of the program; its disadvantage is that improper choice is to optimize, and reduce the performance of the program. Its main products are IBM, Sun's Hotspot. D) Dynamic Optimization, Ahead Of Time Dynamic Optimization, Ahead Of Time Dynamic optimization technology fully utilizes Java source compilation, bytecode compilation, dynamic compilation and static compilation Technology. The original code or bytecode of Java is input, and the output is a mixture of highly optimized executable code and a dynamic library (a DLL file in Window, and the shared library in Unix is a shared library .a .so file). The structure is as follows:
[img] http://www.computerworld.com.cn/htm/app/aprog/01_7_9_3f.gif [/ img] Its advantage is that it can greatly improve the performance of the program; the disadvantage is to destroy Java portability, and Java's security has brought certain hidden dangers. Its main product is TowerJ3.0. Optimize the Java program design and encoding, improve some of the methods of Java program performance. Find the bottleneck in the program by using some of the previously described auxiliary tools, and then optimize the code of the bottleneck portion. There are generally two options: optimizing code or changing design methods. We generally choose the latter, because you don't call the following code to improve program performance than call some optimized code. And a well-designed program can streamline the code to improve performance. Some methods and techniques that are often used in the design and encoding of the Java program, and some methods and techniques that are often used in the design and encoding of the Java program. 1. Adjustment of the generation and size of the object. A common problem in the Java program is that there is no function provided by the Java language itself, which often generates a large number of objects (or instances). Since the system not only takes time to generate an object, it may still take time to take the time to garbage recycling and processing. Therefore, excessive objects will have a big impact on the performance of the program. Example 1: About String, StringBuffer, , and Append Java languages provide operations for String type variables. However, if not used, it will affect the performance of the program. As of the following statement: string name = new string ("HuangWeifeng"); System.out.Println (Name "Is My Name"); seemingly very streamlined, it is not the case. In order to generate binary code, the following steps and operations are processed. (1) Generate a new string new string (STR_1); (2) Copy the string. (3) Load the string constant "HuangWeifeng"; (4) Call the string of the architecture; (5) Save the string into an array (starting from position 0) (6) from Java.io The static OUT variable (7) generates a new string buffer variable in the .printStream class New StringBuffer (STR_BUF_1); (8) Copy the string buffer variable (9) Call string buffer (constructor); (10); (10) ) Save the string buffer to an array (starting from position 1) (11) Taking STR_1 as a parameter, calling the Append method in the string buffer class. (12) Loading the string of the constant "IS my name"; (13) Taking STR_3 as the parameter, call the Append method in the string buffer. (14) Execute the toString command for STR_BUF_1. (15) Call the PrintLn method in the OUT variable, output the result. It can be seen that the two lines of simple code generates STR_1, STR_2, STR_3, STR_4, and STR_BUF_1 five object variables. Examples of these generated classes are generally stored in the heap.
Piles are initialized for all classes, classes of all classes, while also calling an extremely super-class architecture. These operations are very consumed system resources. Therefore, it is necessary to limit the generation of objects. After modification, the above code can be replaced with the following code. StringBuffer name = new stringbuffer; system.out.println ("is my name."). TOSTRING ()); the system will perform the following operations. (1) Generate a new string buffer variable new stringbuffer (STR_BUF_1); (2) Copy the string buffer variable (3) load string constant "huangweifeng" (STR_1); (4) call string buffer architecture ( Constructor); (5) Save the string buffer to an array (starting from position 1) (6) Get static OUT variable from the java.io.printStream class to load STR_BUF_1; (8) loading string often " Is my name "(STR_2); (9) Call the Append method in the StringBuffer instance with STR_2. (10) Execute the toString command for STR_BUF_1. (STR_3) (11) Call the PrintLn method in the OUT variable, output the result. It can be seen that the improved code only generates four object variables: STR_1, STR_2, STR_3 and STR_BUF_1. You may feel that less generation of an object will not increase the performance of the program. However, the execution speed of the code segment 2 below will be twice the code segment 1. Since the code segment 1 generates eight objects, the code segment 2 generates only four objects. Code segment 1: String name = new stringbuffer ("huangweifeng"); name = "is my"; name = "name"; code segment 2: stringbuffer name = new stringbuffer ("HuangWeifeng"); name.Append ("is my "); Name.append (" name. "). TOSTRING (); therefore, fully utilizing the library function provided by Java to optimize the program, is very important to improve the performance of the Java program. The attention points mainly have the following aspects (1) Use static class variables if possible, if the variables in the class do not change with his instance, you can define static variables so that all of his instances share this variable. Example: Public class foo {someObject SO = New someobject ();} You can define as: public class foo {static homeObject so = new someobject ();} (2) Do not make too much changes to generated objects. For some classes (such as: String class), prefer to regenerate a new object instance without modifying the generated object instance. Example: String name = "huang"; name = "wei"; name = "feng"; the above code generates three String type object instances. The first two immediately need system for garbage collection. If you want to connect to a string, performance will be worse. Because the system will not generate more temporary variables for this. As shown in the first example. (3) When the object is generated, many classes to be assigned to it rationally and the size in Java have its default spatial allocation size.
For StringBuffer classes, the default assignment space size is 16 characters. If the size of the StringBuffer is not 16 characters in the program, the correct initialization must be performed. (4) Avoid generating objects or variables shorter or shorter life cycle. For this case, an object buffer pool is defined. It is to manage a smaller cost of managing a target buffer pool than frequent generation and recycling objects. (5) Initialization only within the target scope. Java allows you to define and initialize the object anywhere in your code. In this way, it can be initialized only within the range of the object. Thereby saving the overhead of the system. Example: SomeObject SO = New SomeObject (); if (x == 1) THEN {foo = SO.GETXX ();} can be modified to: if (x == 1) Then {SomeObject SO = New SomeObject (); foo = sol.getxx ();} 2. Try / catch in an exception (Exception) Java language provides TRY / CATCH to facilitate user capture exceptions to process abnormalities. But if you use improper use, it will also affect the performance of the Java program. Therefore, pay attention to the following two points. (1) Avoid logic to the application using TRY / CATCH If you can use the IF, while, etc. can be handled, then do not use the TRY / CATCH statement (2) to reuse an exception to process the exception, Reuse the existing anomaly objects as much as possible. Those in the abnormal process, generating an abnormal object to consume most of the time. 3. Threading A high-performance application usually uses threads. Because threads make full use of the resources of the system. In other threads, the program can continue to process and run because of the other threads waiting for the hard disk or network read and write. However, it is used to use improper use and will affect the performance of the program. Example 2: Correct use of the Vector class Vector is mainly used to save various types of objects (including the same type and different types of objects). However, in some cases, use the performance of the program to bring performance. This is mainly determined by the two features of the VECTOR class. First, Vector provides thread safety protection features. Even many methods in the Vector class synchronize. But if you have confirmed that your application is a single thread, the synchronization of these methods is completely unnecessary. Second, when you look for various objects stored, it often spends a lot of time to match the type. These matches are completely unnecessary when these objects are in the same type.
Therefore, it is necessary to design a single-threaded, saving a specific type object class or a collection to replace the vector class. The program used to replace is as follows: public class stringvector {private string [] data; private int count; public; StringVector () {this (10); // default size is 10} public stringvector (int initialsize) {data = new string [initialsize];} public void add (string str) {// ignore null strings if (string String Strings if (string String Strings if (Str == null) {return;} ensureCapacity (count 1); data [count ] = str;} private void ensureCapacity (int minCapacity) {int oldCapacity = data.length; if (minCapacity> oldCapacity) {String oldData [] = data; INT newcapacity = Oldcapacity * 2; Data = new string [newcapacity]; System.Arraycopy (OldData, 0, DATA, 0, Count);}}} PUBLIC VOID REMOVE (STRING STR) {if (str == null) {Return / / ignore null str} for (int i = 0; i
The procedures for test are as follows: import java.util.vector; public class testcollection {public static void main (string args []) {testcollection collect = new testCollection (); if (args.length == 0 ) {System.Out.println ("usage: java testcollection); system.exit (1);} if (args [0] .Equals (" vector ") {Vector store = new vector ); long start = system.currenttimemillis (); for (int i = 0; i <1000000; i ) {store.addelement ("string");} long finish = system.currenttimemillis (); system.out.println (Finish-start); start = system.currenttimemillis (); for (int i = 0; i <1000000; i ) {string result = (string) Store.Elementat (i);} finish = system.currenttimemillis () System.out.Println (FINISH-START));} else if (args [0] .Equals ("stringvector")) {stringVector store = new stringVector (); long start = system.currenttimemillis (); for INT i = 0; i <1000000; i ) {store.add ("string");} long finish = system.currenttimemillis (); system.out.println; s TART = system.currenttimemillis (); for (int i = 0; i <1000000; i ) {string result = store.getstringat (i);} finish = system.currenttimemillis (); system.out.println ((Finish- START));}}} / * * * * * * * * * * TestCollection.java * * * * * * * * * * * * * * * * / Test results are as follows ( Suppose the standard time is 1, the smaller performance, the better: