-2

In java programming, there are three class(StringTokenizer, Scanner, BufferedReader ) to take input . why Scanner take a long time as compare to bufferereader and DataInputStream .

Scanner

  Scanner s = new Scanner(System.in);
    int n = s.nextInt();

why BufferedReader is fast

    BufferedReader br = new BufferedReader(
        new InputStreamReader(System.in));

    StringTokenizer st
        = new StringTokenizer(br.readLine());
    int n = Integer.parseInt(st.nextToken());
Adarsh Dhakad
  • 347
  • 1
  • 3
  • 10
  • 1
    I could answer your C++ vs Java for competitive coding question. However, it will be my opinion and its not exactly a coding problem and hence it is not suited for SO. – AKSingh Apr 24 '21 at 18:03

1 Answers1

2

Your Scanner is reading smaller bits of information from the input stream, one at a time and without buffering, and this process is slow since the slowest step in the process, reading from the input stream, must be done multiple times.

The whole point of using Buffered input is to allow for more time-efficient reading by reading large chunks of data fewer times from the file and into a buffer, and then extracting the data from the buffer in your code as needed. This way, the bottleneck, reading from the input stream, is greatly reduced.

Have you tried:

Scanner scan = new Scanner(new BufferedInputStream(System.in));

If so, what is the result?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373