Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a very long string from console using Java Scanner takes time?

Currently I'm creating a console program that read a one line with very long String with java Scanner

sample data is more like this

50000 integer in one line separated by white-space,

"11 23 34 103 999 381 ....." until 50000 integer

This data is entered by user via console not from a File

here's my code

        System.out.print("Input of integers : ");
        Scanner sc = new Scanner(System.in);
        long start = System.currentTimeMillis();

        String Z = sc.nextLine();

        long end = System.currentTimeMillis();
        System.out.println("String Z created in "+(end-start)+"ms, Z character length is "+Z.length()+" characters");

Then I execute, as the result I've got this

String Z created within 49747ms, Z character length is 194539 characters

My question is why it takes a long time? Is there any faster way to read a very long string?

I have tried buffered reader, but not much different..

String Z created within 41881ms, Z character length is 194539 characters
like image 317
Angga Saputra Avatar asked Sep 30 '26 15:09

Angga Saputra


1 Answers

It looks like scanner uses a regular expression to match the end of line - this is likely causing the inefficiency, especially since you're matching regex against a 200k length String.

The pattern used is, effectively, .*(\r\n|[\n\r\u2028\u2029\u0085])|.+$

like image 154
mcfinnigan Avatar answered Oct 02 '26 04:10

mcfinnigan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!