Java performance optimization skills highlights (3)

xiaoxiao2021-03-05  21

Third, the content introduced by the GUI article is suitable for the application of graphical user interface (Applet and normal application), to use AWT or SWING.

3.1 Use JAR compressed class files

The Java file (JAR file) is a compressed file according to JavaBean standard, which is the primary and recommended ways to publish JavaBean components. JAR file helps reduce file volume and shorten the download time. For example, it helps Applet increase the start speed. A JAR file can contain one or more related beans and support files such as graphics, sound, HTML, and other resources.

To specify a JAR file in an HTML / JSP file, just join the Archive = "name.jar" declaration in the Applet tag.

3.2 Tips Applet loading process

Have you seen the website that uses Applet, notice that a placeholder appears in a place where you should run Applet? What happens when the applet is downloaded? The biggest possibility is that the user will go out. In this case, the information displayed on an applet is undoubtedly helps to encourage users to wait.

Let's take a look at a specific implementation method. First create a small applet, the applet is responsible for downloading official applets in the background:

import java.applet.Applet; import java.applet.AppletStub; import java.awt.Label; import java.awt.Graphics; import java.awt.GridLayout; public class PreLoader extends Applet implements Runnable, AppletStub {String largeAppletName; Label label Public void init () {// Requires the official applet largeappletname = getParameter ("applet"); // "Please wait" prompt information label = new label ("Please wait ..." largeappletname; add (label);} public void run () {try {// get Applet class to be loaded class largeAppletClass = Class.forName (largeAppletName); // create an instance of the Applet to be loaded Applet largeApplet = (Applet) largeAppletClass.newInstance () ; // Set the Applet's Stub program LargeApplet.setstub (this); // Cancel "Please wait" information Remove (Label); // Setting the layout setLayout (New GridLayout (1, 0)); add (largeapplet); // Display formal applet LargeApplet.init (); LargeApplet.Start ();} catch (exception ex) {// Display error message label.setText ("You cannot load the specified applet");} // Refresh screen Validate (); Public Void AppleTResize (int width, int Height) {// Transfer AppleTResize to a from the Stub program to a Pplet Resize (Width, Height);}

The compiled code is less than 2K, and the download speed is very fast. There are several places in the code worth noting. First, the preloader implements the AppletStub interface. Generally, Applet judges its own codeBase from the caller. In this case, we must call setstub () telling the applet where to extract this information. Another thing that is worth noting is that the AppletStub interface contains many ways with the Applet class, except for the AppleTResize () method. Here we pass the call to the AppleTResize () method to the Resize () method. 3.3 Push it before drawing the graph

ImageOBserver interface can be used to receive prompt information for graphics. The ImageOBserver interface has only one method imageUpdate (), which can draw graphics on the screen with a repaint () operation. An example is provided below.

Public Boolean ImageUpdate (Image IMG, INT FLAGS, INT X, INT Y, INT W, INT H) {IF ((Flags & Allbits)! = 0 {repaint ();} else if (Flags & Error | Abort)) ! = 0) {Error = true; // The file is not found, consider displaying a placeholder repaint ();} return (flags & (allbits | error | abort)) == 0;}

When graphics information is available, the ImageUpdate () method is called. If further update is needed, the method returns true; if the required information has been obtained, the method returns false.

3.4 Cover UPDATE Method

The default action of the update () method is to clear the screen and then call the Paint () method. If you use the default Update () method, frequent use of graphics can display flicker. To avoid the screen clearance operation before Paint () call, you only need to override the update () method according to the following:

Public void Update (graphics g) {Paint (g);

The more ideal solution is to override Update (), only the area that changes on the screen, as shown below:

Public Void Update (Graphics G) {g.clipRect (x, y, w, h); Paint (g);}

3.5 Delayed Heavy Picture Operation

For the application of the graphical user interface, the main reason why performance is often the efficiency of the heavy picture screen. This is usually obvious that the user changes the window size or scrolls one window. Changing the window size or the operation such as scrolling screen results in a large number of flash events to generate, and even exceeds the execution speed of the relevant code. The best way to deal with this problem is to ignore all "late" events.

It is recommended to introduce a few milliseconds here, that is, if we immediately receive another heavy draw event, stop processing the current event to handle the finals that the last received heavy draw event; otherwise, we continue to carry out the current heavy blow.

If the event is to start a time consuming, it is a good way to process a work thread; otherwise, some parts may be "freeze" because only one event can be handled each time. A simple example of an event handling is provided below, but it can be used to control the working thread after expansion.

Public Static Void Runonce (String ID, Final Long Milliseconds) {synchronized (e_queue) {// e_queue: Collection IF (! E_Queue.containskey (ID)) {e_queue.put (token, new last ";} } Final lastone lastone = (lastone) E_QUEUE.GET (TOKEN); Final Long Time = System.currentTimeMillis (); // Get Current Time Lastone.Time = Time; (New Thread () {Public Void Run () {IF MilliseConds> 0) {Try {thread.sleep (MilliseConds);} // Suspension thread ATCH (Exception EX) {}} Synchronized (Lastone.Running) {// Waiting for the last event end IF (Lastone.Time! = Time) // only process the last event return;}}}). Start ();} private static hashtable e_queue = new hashtable (); private static class lastone {public long time = 0; public object running = new object ();} 3.6 Use a double buffer

A buffer drawing outside the screen, and immediately display the entire graph immediately after completion. Because there are two buffers, the program can switch back and forth. In this way, we can use a low priority thread to draw, so that the program can perform other tasks with idle CPU times. The pseudo code fragment below demonstrates this technology.

Graphics myGraphics; Image myOffscreenImage = createImage (size () width, size () height..); Graphics offscreenGraphics = myOffscreenImage.getGraphics (); offscreenGraphics.drawImage (img, 50, 50, this); myGraphics.drawImage (myOffscreenImage, 0 , 0, THIS);

3.7 Using BufferedImage

Java JDK 1.2 uses a soft display device that makes text look similar on different platforms. To implement this feature, Java must directly process pixels that make up text. Since this technique is to be done in memory, early JDK is in poor performance in using this technology. The Java standard proposed to solve this problem has achieved a new graphic type, which is bufferedimage.

The BufferedImage subclass describes the graphic with an accessible graphics data buffer. A bufferedImage contains a ColorModel and a set of raster graphics data. This class generally uses the RGB (red, green, blue) color model, but it can also handle grayscale graphics. Its constructor is simple, as shown below:

Public BufferedImage (int Width, Int Height, int imagetype)

ImageType allows us to specify what type of graphic to buffer, such as 5-bit RGB, 8-bit RGB, grayscale, etc.

3.8 Using VolatileImage

Many hardware platforms and their operating systems provide basic hardware acceleration support. For example, hardware acceleration typically provides rectangular filling, and hardware acceleration is more efficient than using CPUs to complete the same task. Since the hardware accelerates a part of the work, multiple workflows are allowed to perform concurrent, thereby alleviating the pressure on the CPU and the system bus, so that the application can run faster. Use VolatileImage to create hardware accelerated graphics and the content of management graphics. Since it directly uses the ability to use low-level platforms, the degree of improvement in performance depends primarily on the graphical adapter used by the system. The content of VolatileImage may be lost at any time, that is, it is "Volatile". Therefore, it is best to check if its content is lost before using the graph. VolatileImage has two ways to check whether the content is lost: Public Abstract Int Validate (GraphicsConfiguration GC); Public Abstract Boolean Contentslost ();

You should call the validate () method each time you copy content or write to VolatileImage, you should call the VOLATILATIMAGE object. The contentslost () method tells us that since the last Validate () call, the content of the graph is lost.

Although VolatileImage is an abstract class, don't send a child class from it. VolatileImage should be created by Component.createVolatileImage () or GraphicsConfiguration.createCompaVolatileImage () method.

3.9 Using Window Blitting

When scrolling operation, all visible content generally want to scroll, resulting in a lot of unnecessary heavy paintings. Many operating systems of graphic subsystems, including Win32 GDI, MacOS, and X / Windows, support Window Blitting Technology. Window Blitting technology moves the graphics directly to a new location in the screen buffer, only the new area. To use Window Blitting technology in Swing applications, the setting method is as follows:

SetscrollMode (int mode);

In most applications, this technique can be used to improve scrolling speed. Only in one case, Window Blitting will result in a reduction in performance, that is, the application is scrolling in the background. If the user is scrolling an application, it is always at the front desk, there is no need to worry about any negative impact.

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

New Post(0)