Does closing Scanner affect performance

308 views Asked by At

I was solving a competitive problem and in problem, I was taking user input using scanner.
These are 2 code segments, one closing scanner and one without closing scanner.

Closing scanner

import java.util.Scanner;

public class JImSelection {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = Integer.valueOf(scanner.nextLine());
        while (n-- > 0) {
            double number = (Math.log(Long.valueOf(scanner.nextLine())) / Math.log(2));
            System.out.println((int) number - number == 0 ? "Yes" : "No");
        }
        scanner.close();
    }
}

Not closing scanner

import java.util.Scanner;

public class JImSelection {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = Integer.valueOf(scanner.nextLine());
        while (n-- > 0) {
            double number = (Math.log(Long.valueOf(scanner.nextLine())) / Math.log(2));
            System.out.println((int) number - number == 0 ? "Yes" : "No");
        }           
    }
}

The first one (closing scanner) give me score 14.47,
and second one (not closing scanner) gives 15.22.
I think compiler is freeing the resource when i use scanner.close(); and that is why there is a difference in the scores.

This is the score judge formula.

It is assigned a score of 100. Suppose, you submit a solution of n characters, then your score is (56/n)*100.

1

There are 1 answers

3
Erwin Bolwidt On BEST ANSWER

It is assigned a score of 100. Suppose, you submit a solution of n characters, then your score is (56/n)*100.

You're kidding right? The score for one solution is 14.47. This means that your source code was 56 / (14.47/100) =~= 387 characters.(=~= for a lack of a "about equals" symbol)

In the other instance, you had a score of 15.22, which means that your source code was 56 / (15.22/100) =~= 368 characters long.

A difference of 29 characters, which is probably the length of your line of source code that says scanner.close(); (including leading spaces, two trailing spaces and a carriage return/line feed pair)

This has nothing to do with the performance of your code.