簡體   English   中英

Java循環對象聲明的最佳實踐

[英]Java loop object declaration best practice

我已經閱讀了一些關於在循環內聲明對象的其他問題,例如:

聲明單個對象或將匿名對象循環到ArrayList是更好的做法嗎?

Java:在循環中聲明對象

但都沒有真正解決我的問題。

我正在重復掃描用戶輸入並創建一個類來解析每次迭代時的字符串:

    public static void main(String[] args) {
        while (true) {
            System.out.print("Enter a string of brackets to test: ");
            String exp = new Scanner(System.in).nextLine().trim();
            if (exp.equals("q")) break; // q is the 'quit' flag
            System.out.println(new BracketMatcher(exp.length()).parse(exp));
        }
    }

這個區塊在性能方面 ,而不是范圍方面有什么不同嗎?:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    BracketMatcher matcher;
    while (true) {
        System.out.print("Enter a string of brackets to test: ");
        String exp = input.nextLine().trim();
        if (exp.equals("q")) break; // q is the 'quit' flag
        matcher = new BracketMatcher(exp.length());
        System.out.println(matcher.parse(exp));
    }

我最好不要在BracketMatcher中使用parse()作為靜態方法,因為我只使用那個方法嗎?

謝謝。

代碼中的性能差異來自於在每次迭代中創建一個新的掃描儀(這很愚蠢,甚至可能無法可靠地運行,具體取決於掃描儀的緩沖方式)。

聲明變量的地方本身沒有性能影響。

我個人會創建一次掃描器(因為它應該讀取所​​有行,而不僅僅是一行),但循環內部的BracketMatcher(因為它綁定到當前行)。

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    while (true) {
        System.out.print("Enter a string of brackets to test: ");
        String exp = input.nextLine().trim();
        if (exp.equals("q")) break; // q is the 'quit' flag
        System.out.println(new BracketMatcher(exp.length()).parse(exp));
    }
}

我最好不要在BracketMatcher中使用parse()作為靜態方法,因為我只使用那個方法嗎?

我不知道你的BracketMatcher做了什么,無論輸入什么都可以做好准備。 例如,可以為固定表達式編譯一次正則表達式匹配器,然后重復使用許多字符串進行匹配。 在這種情況下,您可以將BracketMatcher保留為有狀態對象,並在循環外創建一次。

分配new Scanner(...)通常會比重新使用對象更少執行。 特別是如果對象本身沒有內部狀態 - 那么每次分配一個新狀態對你沒有任何幫助。

所以是的,我會說每個都做一個並重新使用它們。

我最好不要在BracketMatcher中使用parse()作為靜態方法,因為我只使用那個方法嗎?

如果BracketMatcher包含任何狀態,則可以將其BracketMatcher靜態方法。

如果您多次創建掃描程序,則會導致性能下降(因為垃圾收集和構建它),並且由於垃圾郵件輸入掃描程序而導致系統稍微變得笨拙

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM