Update 1: Added walk2 by pushing to stack.
Update 2: The string length now obtained inside C.
Update 3: Changed from for loop to while loop.
Ah, I tried Inline::C. Walk1 runs faster than split in older Perl <= 5.20.x.
...
use Inline 'C' => <<'END_C';
#include <stdlib.h>
#include <string.h>
SV * c_walk1(SV *sv)
{
STRLEN len;
const char *s = SvPV_const(sv, len);
const char *m = s, *strend = s + len;
AV *ret = newAV();
while (s < strend) {
if (*s++ == '\n') {
av_push(ret, newSVpvn(m, s - m));
m = s;
}
}
return newRV_noinc((SV *) ret);
}
void c_walk2(SV *sv)
{
STRLEN len;
const char *s = SvPV_const(sv, len);
const char *m = s, *strend = s + len;
Inline_Stack_Vars;
Inline_Stack_Reset;
while (s < strend) {
if (*s++ == '\n') {
Inline_Stack_Push(sv_2mortal(newSVpvn(m, s - m)));
m = s;
}
}
Inline_Stack_Done;
}
END_C
# walk1 - receive array ref
{
my $string = $huge_string;
my $start = time;
my $lines = c_walk1($string);
printf "duration walk1: %0.3f seconds\n", time - $start;
printf "%d lines\n\n", scalar(@$lines);
}
# walk2 - receive list
{
my $string = $huge_string;
my $start = time;
my @lines = c_walk2($string);
printf "duration walk2: %0.3f seconds\n", time - $start;
printf "%d lines\n\n", scalar(@lines);
}
Output from Perl 5.20.3 and Perl 5.26.1
$ /opt/perl-5.20.3/bin/perl demo.pl
duration memfh: 0.526 seconds
917504 lines
duration regex: 0.448 seconds
917504 lines
duration split: 0.110 seconds
917504 lines
duration trim : 0.268 seconds
917504 lines
duration walk1: 0.073 seconds
917504 lines
duration walk2: 0.110 seconds
917504 lines
$ /opt/perl-5.26.1/bin/perl demo.pl
duration memfh: 0.479 seconds
917504 lines
duration regex: 0.442 seconds
917504 lines
duration split: 0.066 seconds
917504 lines
duration trim : 0.259 seconds
917504 lines
duration walk1: 0.070 seconds
917504 lines
duration walk2: 0.084 seconds
917504 lines
Regards, Mario