Question
I've just started getting back into Java recently and never had an opportunity to use try-with-resources
. On the surface it looks great as it can cut down on code, but under the hood is it more or less expensive of an operation than the traditional try-catch
? I know try-catch
already is an expensive operation, hence my curiosity.
I gave both types a simple test and didn't notice much of a difference at all:
Test Examples
Try-With-Resources Test
long startTime = System.currentTimeMillis();
ArrayList<String> list = null;
try (Scanner sc = new Scanner(new File("file.txt"))) {
list = new ArrayList();
while (sc.hasNext()) {
list.add(sc.next());
}
} catch (Exception ex) {
System.err.println("Error: " + ex.getMessage());
} finally {
long endTime = System.currentTimeMillis();
System.out.println("The program completed in " + (endTime - startTime) + " ms");
}
Traditional Try-Catch Test
long startTime = System.currentTimeMillis();
ArrayList<String> list = null;
Scanner sc = null;
try {
sc = new Scanner(new File("file.txt"));
list = new ArrayList();
while (sc.hasNext()) {
list.add(sc.next());
}
} catch (Exception ex) {
System.err.println("Error: " + ex.getMessage());
} finally {
sc.close();
long endTime = System.currentTimeMillis();
System.out.println("The program completed in " + (endTime - startTime) + " ms");
}
Results
Both resulted in a time of 15-16ms - no real noticeable difference at all. But admittedly this is a very small test example.
My question again: Under the hood is try-with-resources
more or less expensive than a traditional try-catch
?