Does closing Scanner affect performance

人走茶凉 提交于 2019-12-23 12:42:48

问题


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:


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.



来源:https://stackoverflow.com/questions/30704936/does-closing-scanner-affect-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!