尝试解决资源性能问题

时间:2020-07-10 12:24:51

标签: performance try-catch bufferedreader try-with-resources

在最近的代码审查中,一位同事建议使用“尝试使用资源声明”。所以我用谷歌搜索并更改了代码。

我正在使用Java 11中的API的预期结果来测试600行CSV。因此,对于每个CSV行,我都会发出一个get请求。进行更改之后,我发现我的测试花费的时间增加了±30%(取决于API响应)。经过调查,我发现了问题所在,但我不明白为什么会这样。

这是MR之前的代码:

   <Application.Resources>
         <ResourceDictionary>
             <ResourceDictionary.MergedDictionaries>
                 <ResourceDictionary Source="Resources/MainTheme.xaml"></ResourceDictionary>

                <ResourceDictionary Source="Resources/Window.xaml"></ResourceDictionary>       
             </ResourceDictionary.MergedDictionaries>
         </ResourceDictionary>
    </Application.Resources>

Before the changes

带有“尝试资源”的代码:

 public static String getApiResponseBody(HttpURLConnection con) throws IOException {
    String inputLine = null;
    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    try {
        inputLine = in.readLine();
        in.close();
        con.disconnect();
    } catch (IOException e) {
        error.error("Can't get API response! " + e);
    }
    return inputLine;
}

try with resources

这是我解决性能问题的方法:

public static String getApiResponseBody(HttpURLConnection con) {
        String inputLine = null;
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()))) {
            inputLine = in.readLine();
            con.disconnect();
        } catch (IOException e) {
            error.error("Can't get API response! " + e);
        }
        return inputLine;
    }

closing BufferedReader in try with resources

因此,从阅读开始,BufferedReader实现了Closable,因此,如果使用“尝试使用资源”,则无需关闭它。另外,当我使用“最终捕获托盘”块时,Intellij建议将其替换为“尝试资源”,并自动删除 in.close(); 。 我真的很想了解这里发生了什么。对于600条线来说,性能问题并不是那么重要,但是我需要将测试扩展到50万条线,所以差异为±30%。 谢谢!

0 个答案:

没有答案