开发者

Comparison of input statements in java

Two statements which more or less do the same job of inputting an int

int foo = new Scanner(System.in).nextInt();

and

int bar = Integer.parseInt(new Scanner(System.in开发者_JAVA技巧).next());

Is there any performance difference between them..???????????


The time it takes to blink is about 50 milli-seconds. The time to press a key is about the same. The difference between these statement will be far less than this and will be less than 0.002 milliseconds.

In short, I wouldn't worry about it. Make it correct, clear and simple, and this is often the fastest as well.


I honestly don't think you should be thinking in terms of efficiency here, especially since you seem to use it for a local variable, and you throw away the (newly created) Scanner in either case.

But if it's still of interest, I'd say that the performance difference is negligible, since the Scanner.nextInt ends with a

return Integer.parseInt(s, radix);

anyway.

If you need to parse several integers, I would say the best way to create a Scanner once, and reuse that instance:

Scanner scanner = new Scanner(System.in);
int foo = scanner.nextInt();
int bar = scanner.nextInt();
// ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜