Reading array of integers readln performance issues

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 11 13:54:51 PDT 2015


On Thursday, 11 June 2015 at 19:56:00 UTC, kerdemdemir wrote:
> Can I achieve something faster than code below?
>
> auto peopleMoney = stdin.readln().split().map!(a => 
> to!int(a)).array();
> if (peopleMoney.length == 200000)
> 	 writeln(":(");

`std.array.split` is eager. It may be faster if you use the lazy 
`std.algorithm.splitter`:

auto peopleMoney = stdin.readln().splitter().map!(to!int).array();

[...]
> Ps: I do not want to bore you with long code, but I am sending 
> link to whole program anyway if anyone need.
>  http://codeforces.com/contest/549/submission/11537206

Seeing that you get the number of elements beforehand, you can 
preallocate the array, avoiding relocations of the data as 
elements are appended:

peopleMoney = new int[peopleCount];
copy(stdin.readln().splitter().map!(to!int), peopleMoney);

But these are tweaks. They may improve performance a little, but 
it won't be drastic.

And anyway, I find it hard to believe that the original version 
takes more than a second to parse the input. Maybe try returning 
from the function in addition to printing ":(". Otherwise the 
program goes on, and the site may not show the output if the 
program as a whole took too long.


More information about the Digitalmars-d-learn mailing list