Java performance optimization skills

xiaoxiao2021-03-06  22

=================================== summary: ============== ====================== The resources (memory, CPU time, network bandwidth, etc.) are available, and the purpose of optimization is to make the program Maybe few resources complete the predetermined task. Optimization usually contains two aspects: reduce the volume of the code, improve the operating efficiency of the code. This paper discussed how mainly how to improve the efficiency of code.

=================================== Outline: ============= ===== =============== 1 Variable 1.5 Try to specify the Final modifier 1.6 to use local variables 1.7 multiplication and division II. J2EE 2.1 Use Buffer Terminal 2.2 Always pass the session bean Access Entity Bean 2.3 Select the appropriate reference mechanism 2.4 Setting read only attributes in the deployment descriptor 2.5 Bush Visits for EJB HOME 2.6 Implementing local interfaces for EJB 2.7 Generating primary key 2.8 timely clearing no longer need session 2.9 Close Using useless session 2.10 Servlet and memory use 2.12 HTTP Keep-Alive 2.12 JDBC and Unicode 2.13 JDBC I / O 1.14 Memory Database 3, GUI Article 3.1 Tips with JAR Compressed Class 3.2 Prompt Applet Load Process 3.3 Pre-put it before drawing graphs 3.4 override UPDATE Method 3.5 Delayed Heavy Pictures 3.7 Use BufferedImage 3.8 Using VolatileImage 3.9 using Window Blitting 4, supplementing data =================================== ========================================================================================================================================================================================================================= ================================ 1, the issue of universal "universal article" is suitable for most Java applications. 1.1 Do not create a class with a new keyword to create an instance of a class with a new keyword, all constructor in the constructor is automatically called. But if an object implements a Cloneable interface, we can call its clone () method. The clone () method does not call any class constructor. In the case of design mode (Design Pattern), if you create an object with a Factory mode, you can use the Clone () method to create a new object instance is very simple.

For example, the following is a typical implementation of the Factory mode: public static credit getNewcredit () {return new credit ();} Improved code uses a clone () method, as follows: private static credits Static Credit getNewcredit () {return (Credit) Basecredit.clone ();} The above ideas is also useful for array processing. 1.2 Using Non-Block I / O Local JDK does not support non-blocking I / O APIs. In order to avoid I / O blocking, some applications use a way to create a large number of threads (in better case, using a buffer pool). This technology can be seen in many applications that must support concurrent I / O streams, such as web servers, quotes, and auction applications. However, creating a Java thread requires considerable overhead. JDK 1.4 introduces a non-blocking I / O library (Java.nio). If the application requires a version earlier JDK, there is a package that supports non-blocking I / O. See the "Adjust Java I / O Performance" of the Sun China website. 1.3 Cautious use of abnormal abnormalities is unfavorable. Throw an exception first to create a new object. The constructor of the Throwable interface calls the local (Native) method called FillInstackTrace (), and the FillInstackTrace () method checks the stack to collect the trace information. As long as there is an abnormality being thrown, the VM must adjust the calling stack because a new object is created during the processing. An exception can only be used for error processing, and should not be used to control the program process. 1.4 Do not repeat the initialization variable By default, when the class constructor is called, Java initializes the variable into a determined value: all objects are set to null, integer variables (Byte, Short, int, long) set to 0, float The Double variable is set to 0.0, and the logical value is set to false. This should especially note when a class is derived from another class, because all constructors in the constructor chain are automatically called when creating an object with the New keyword. 1.5 Try to specify the class of Final modifiers with the Final modifier class is not born. In the Java core API, there are many examples of Final, such as java.lang.string. Specifying Final for String class to prevent people from overwriting the Length () method. Also, if you specify a class for Final, all methods of this class are Final. The Java compiler looks for all the Final methods of inline (this and the specific compiler implementation). This move enables performance average by 50%. 1.6 Try to use the local variable calling method to transfer the parameters and the temporary variables created in the call are saved in the stack (STACK), the speed is faster. Other variables such as static variables, example variables, etc. are created in the heap, slower speed. In addition, dependent on specific compiler / JVM, local variables may also be further optimized. See "Using Stack Variables as much as possible." 1.7 Multiplication and division Consider the following code: for (VAL = 0; Val <100000; VAL = 5) {alterx = val * 8; myresult = val * 2;} Replacement multiplication with shift operation can greatly improve performance .

The following is the modified code: for (VAL = 0; VAL <100000; val = 5) {alterx = val << 3; myresult = val << 1;} Modified code no longer multiplied by 8 operation Instead, the one-to-excess left shift 3-bit operation is changed, and one bit per left is equivalent to multiplying 2. Accordingly, the right shift 1 bit operation corresponds to division by 2. It is worth mentioning that although the shift is fast, it may make the code difficult to understand, so it is best to add some comments. Second, J2EE The improvement performance technique in the previous introduction is suitable for most Java applications, and the problem to be discussed is suitable for applications of JSP, EJB or JDBC. 2.1 Use the buffer marker Some application servers add JSP-oriented buffer tag. For example, BEA's WebLogic Server starts supporting this feature from version 6.0, and the Open Symphony project also supports this feature. The JSP buffer tag can buffer the page segment and can buffer the entire page. When the JSP page is executed, if the target segment is already in the buffer, the code generated by generating the piece is not executed. Page-level buffer capture requests for the specified URL and buffer the entire result page. This feature is extremely useful for the homepage of the shopping basket, catalog, and portal. For such applications, the page-level buffer can save the result of the page execution, and the subsequent request is used. For code logic complex pages, the effect of improving performance using buffer marks is more obvious; contrary, the effect may be slightly coupled. See "Improve the performance and stability of JSP applications" with buffer technology. 2.2 Always access entity beans directly through the session bean Access entity bean is not conducive to performance. Each GET method is a remote call when the client remotely accesses entity beans. Session beans accessed to access entity beans are local, and all data can be organized into a structure and then returns its value. Access to entity beans can improve transaction management because session beans will only be submitted when the transaction boundary is reached. Each direct call to the GET method generates a transaction, and the container will perform a "load-read" operation after each entity bean's transaction. Time, using entity beans will lead to poor performance. If the unique use of entity beans is to extract and update data, it is changed to use the JDBC access database within session beans to get better performance. 2.3 Selecting the appropriate reference mechanism In a typical JSP application, the header, the footer section is often extracted, then introduced to the header and footer as needed. Currently, there are two ways to introduce external resources in the JSP page. There are two: include instructions, and the include action. Include instruction: for example <% @ include file = "Copyright.html"%>. This instruction introduces the specified resource when compiling. Before compiling, the pages with the include instructions and the specified resources are merged into one file. The referenced external resource is determined when compiling is more efficient than running. Include Action: For example . This action introduces the result generated after the specified page execution. Since it is completed at runtime, the control of the output results is more flexible. However, when the referenced page cannot be determined when the referenced page is not determined when the referenced content is frequently changed, or when the request is not appeared on the main page, the use of the include action is used. 2.4 Setting Reading Descriptors in Deployment Descriptors Allows all GET methods to be "read only". When a transaction unit is only included with a method of performing a read operation, setting the read-only property is conducive to improve performance because the container does not have to perform a storage operation.

2.5 Buffering The access ejb home interface of EJB Home is available through the JNDI name. This operation requires considerable overhead. JNDI looks up in the init () method of servlet. If you frequent EJB access frequently, you will be best to create an EJBHomeCacche class. The EJBHomeCache class should generally be implemented as a Singleton. 2.6 Implementing the local interface for EJB The local interface is the new content of the EJB 2.0 specification, which makes the bean to avoid overhead of remote calls. Consider the following code. PayBeanHome home = (PayBeanHome) javax.rmi.PortableRemoteObject.narrow (ctx.lookup ( "PayBeanHome"), PayBeanHome.class); PayBean bean = (PayBean) javax.rmi.PortableRemoteObject.narrow (home.create (), PayBean. Class); The first statement means that we are looking for the Home interface. This lookup is made through JNDI, it is an RMI call. Then, we locate the remote object, return to the proxy reference, which is also a RMI call. The second statement demonstrates how to create an instance, involving the Stub program that creates a IIOP request and transmits the request on the network, which is also a RMI call. To achieve a local interface, we must modify the following: Method can no longer throw up java.rmi.RemoteException, including exceptions derived from RemoteException, such as TransactionRequiredException, TransactionRolledBackexception, and NosuChobjectException. EJB provides equivalent local exception, such as TransactionRequiredLocalexception, TransactionRolledBackLocalexception, and NosuchobjectLocalexception. All data and return values ​​are passed in a reference, not the transmission value. The local interface must be used on the machine deployed by the EJB. In short, the client and components of the service must run on the same JVM. If the bean implements a local interface, its reference is not serialized. See "Improve EJB Access Efficiency with local reference". 2.7 Generating the primary key There are many ways to generate primary keys within EJBs, and several common methods are analyzed below and their characteristics. Use the identification mechanism built in the database (SQL Server's Identity or Oracle's Sequence). The disadvantage of this method is that EJB portability is poor. The primary key value (such as incremental operation) is calculated from the entity bean. Its disadvantage is that the transaction can be serialized and the speed is slow. Use clock services such as NTP. This requires a local code for a particular platform to secure the bean to a particular OS. In addition, it also leads to such a possibility that two primary keys are generated within the same millisecond on the multi-CPU server. Borrow for Microsoft's ideas, create a GUID in the bean. However, if you do not help JNI, Java cannot determine the MAC address of the NIC; if you use JNI, the program is to depend on a specific OS. There are several other ways, but these methods are the same limitations. It seems that only one answer is ideal: combined with RMI and JNDI. First bind the RMI remote object to the JNDI tree through the RMI registration. The client is looking for through JNDI.

Here is an example: public class keyGenerator extends UnicastRemoteObject implements Remote {private static long KeyValue = System.currentTimeMillis (); public static synchronized long getKey () throws RemoteException {return KeyValue ;} 2.8 timely removal session is no longer required to remove not Active session, many application servers have default session timeout, generally 30 minutes. When the application server needs to save more sessions, if the memory capacity is insufficient, the operating system shifts some memory data to disk, and the application server may also turn some unusual session according to the "most recent use" algorithm. Store to disk, may even throw "insufficient memory" exception. In a large-scale system, the cost of serialized sessions is very expensive. When the session is no longer needed, the httpsession.invalidate () method should be invoked to clear the session. HttpSession.INValidate () method can usually be called at the application's exit page. 2.9 Close Using Use in the JSP page For pages that do not need to track session status, close the automatically created session can save some resources. Use the following PAGE instructions: <% @ page session = "false"%> 2.10 servlet and memory use many developers to save a lot of information to the user session. Time, the object stored in the session does not have a timely manner to be recycled by the garbage collection mechanism. From the performance, the typical symptom is that the user feels that the system is periodically slow, but it is not possible to attribute the reason to any particular component. If you monitor the heap space of the JVM, its performance is that the memory is not properly larger. There are two main ways to solve such memory problems. The first method is to implement the HTTPSessionBindingListener interface in the BEAN of the session. Thus, as long as the valueUnbound () method is implemented, the resources used by the bean can be explicitly released. Another way is to invalid the session as soon as possible. Most application servers have options for setting sessions as waste intervals. In addition, you can also call the session's setMaxinActiveInterVal () method in a program, which is used to set the maximum interval of the client requests allowed by the servlet container before the invalid session. 2.11 HTTP Keep-Alive Keep-Alive features continue to be valid for the client to the server-side connection. When there is a subsequent request to the server, the Keep-Alive function avoids establishing or re-establishing the connection. Most web servers on the market, including IPlanet, IIS, and Apache, HTTP Keep-Alive supports. This feature is usually useful for sites that provide static content. However, there is another problem with the burden heavier website: although there is a certain advantage of reserved the open connection, it also affects performance, because during the handling of the suspension, the resources that can be released are still occupied. . When the web server and the application server run on the same machine, the KEEP-Alive function has a high impact of resource utilization. 2.12 JDBC and Unicode want you to know some measures to improve performance when using JDBC, such as using a connection pool, correctly selecting stored procedures and direct SQL, deleting extra columns from the result set, and pre-compiling SQL statements, and so on.

转载请注明原文地址:https://www.9cbs.com/read-39897.html

New Post(0)