Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> Linux資訊 >> 更多Linux

用「惰性」建構提升 Java GUI 的啟動效能

問題與思路

緩慢的圖形介面是 Java 最常被抱怨的效能問題之一。構造快速的 GUI 往往既費時又費力,但用了本文這個類,你只需做少量修改就能明顯加速;對彻底的 GUI 改善而言這只是第一步,但因為夠簡單,很多時候效果已經足夠。

方法一句話說完:直到需要時才建構 GUI 元件。宏觀上這是所有 Java 程式的預設行為——誰會在初始化時就把所有可能的視窗都造出來?但這個類讓你能做更細粒度、更惰性的建構。

設計依據三點經驗:第一,多數 GUI 面板很簡單,不需額外功夫就能快速初始化;真正拖慢啟動的是把大量元件堆在一個面板上,而這些面板主要屬於兩類——帶標籤(CardLayout)的面板與滾動面板。第二,通常直到要檢視某個元件時才需要建構它。第三,只有在下列方法之一被呼叫之後元件才會可見:

paint(Graphics)          paintComponents(Graphics)
paintAll(Graphics)       update(Graphics)
repaint()                repaint(long)
repaint(int,int,int,int) repaint(long,int,int,int,int)

因此做法是:把大部分 GUI 建構程式碼從初始化區塊與建構子移到名為 lazyConstructor() 的函式裡,再由這個面板類保證任何繪製或更新方法被呼叫前,lazyConstructor() 至少執行過一次。用在標籤面板裡,因為最初只需建構可見的那一頁,整體構造速度就快了。

實作

import java.awt.*;

public abstract class LazyPanel extends Panel {
    private boolean lazyConstructorCalled = false;
    private boolean isConstructorFinished = false;

    protected LazyPanel() {
        isConstructorFinished = true;
    }

    public void paint(Graphics g) {
        callLazyConstructor();
        super.paint(g);
    }

    public void paintAll(Graphics g) {
        callLazyConstructor();
        super.paintAll(g);
    }

    public void paintComponents(Graphics g) {
        callLazyConstructor();
        super.paintComponents(g);
    }

    public void repaint() {
        callLazyConstructor();
        super.repaint();
    }

    public void repaint(long l) {
        callLazyConstructor();
        super.repaint(l);
    }

    public void repaint(int i1, int i2, int i3, int i4) {
        callLazyConstructor();
        super.repaint(i1, i2, i3, i4);
    }

    public void repaint(long l, int i1, int i2, int i3, int i4) {
        callLazyConstructor();
        super.repaint(l, i1, i2, i3, i4);
    }

    public void update(Graphics g) {
        callLazyConstructor();
        super.update(g);
    }

    /** 只做一次;之後再呼叫不執行任何動作。 */
    public synchronized final void callLazyConstructor() {
        if ((lazyConstructorCalled == false) && (getParent() != null)) {
            lazyConstructor();
            lazyConstructorCalled = true;
            validate();
        }
    }

    /** 子類必須實作;原本寫在建構子裡的元件建立程式碼大多搬到此處。 */
    abstract protected void lazyConstructor();
}

注意:若子類覆寫了上述任何一個方法,必須在該方法中先呼叫父類的實作,否則惰性建構不會觸發。isConstructorFinished 這道旗標是因為某些 Swing 版本會在元件被加入容器前先呼叫 paint(),我們不希望那時就急著建構。

使用方式

class BusyPanel extends LazyPanel {
    public BusyPanel(int rows, int cols) {
        this.rows = rows;
        this.cols = cols;
    }

    protected void lazyConstructor() {
        setLayout(new GridLayout(rows, cols));
        for (int i = 0; i < rows * cols; ++i) {
            add(new Button(Integer.toString(i + startValue)));
            ++startValue;
        }
    }

    static private int startValue = 0;
    private int rows;
    private int cols;
}

class TestFrame extends Frame {
    public TestFrame() {
        setLayout(new BorderLayout());
        add(nextButton, "South");

        framePanel.setLayout(layout);
        for (int i = 0; i < 30; ++i)
            framePanel.add(new BusyPanel(8, 8), "");
        add(framePanel, "Center");

        nextButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                layout.next(framePanel);
            }
        });
        setSize(400, 300);
    }

    private CardLayout layout = new CardLayout();
    private Button nextButton = new Button("Next Panel");
    private Panel framePanel = new Panel();

    static public void main(String args[]) {
        (new TestFrame()).show();
    }
}

驗證效果與注意事項

想親眼確認差異,把 lazyConstructor() 裡的程式碼搬回 BusyPanel 建構子、重新編譯再跑一次,啟動時多出來的延遲就是這個類要消除的 overhead。

這套做法對 Swing 同樣有效,只要讓 LazyPanel 改為繼承 JPanel 即可。

使用上有一點要小心:不要在 lazyConstructor 中丟出例外。面板的建構往往在繪製流程中被觸發,此時拋出例外會讓問題變得難以追蹤,請在裡面自行攔截並處理錯誤。

Copyright © Linux教程網 All Rights Reserved