Big Money
Big Money

Reputation: 10068

Is it more resource efficient to close a scanner or reassign it?

For example if I had

Scanner scan = new Scanner(System.in);
scan.close();
scan = new scanner(new File("file.txt"));

would that be faster than

Scanner scan = new Scanner(System.in);
scan = new scanner(new File("file.txt"));

Or is it essentially the same runtime and uses the same resources?

Thanks

Upvotes: 0

Views: 128

Answers (1)

When you do scan.close() you are freeing the underlying resource. Not calling the function is faster (even if it was a no-op, there is some time associated with performing a call and return), but will likely result in the resource being held open (and possibly locked) by your program until your program exits.

Upvotes: 1

Related Questions