Created
May 29, 2010 00:37
-
-
Save schwern/417919 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use strict; | |
| use warnings; | |
| my $File = "/etc/passwd"; | |
| use Benchmark "cmpthese"; | |
| sub schwern { | |
| my($fh, $limit) = @_; | |
| my $char; # avoid reallocating it every iteration | |
| my $str = ''; | |
| for(1..$limit) { | |
| $char = getc $fh; | |
| last unless defined $char; | |
| $str .= $char; | |
| last if $char eq "\n"; | |
| } | |
| return $str; | |
| } | |
| sub schwern_ref { | |
| my($fh, $limit, $strref) = @_; | |
| return if eof $fh; | |
| my $char; # avoid reallocating it every iteration | |
| $$strref = ''; | |
| for(1..$limit) { | |
| $char = getc $fh; | |
| last unless defined $char; | |
| $$strref .= $char; | |
| last if $char eq "\n"; | |
| } | |
| return 1; | |
| } | |
| sub schwern_alias { | |
| my($fh, $limit) = @_; | |
| return if eof $fh; | |
| my $char; # avoid reallocating it every iteration | |
| $_[2] = ''; | |
| for(1..$limit) { | |
| $char = getc $fh; | |
| last unless defined $char; | |
| $_[2] .= $char; | |
| last if $char eq "\n"; | |
| } | |
| return 1; | |
| } | |
| sub jrandom($$) { | |
| my ($fh, $len) = @_; | |
| my $buf = ''; | |
| my $i; | |
| my $end = $len-1; | |
| for $i (0..$end) { | |
| my $n = read $fh, $buf, 1, $i; | |
| last if !$n || substr($buf, $i, 1) eq "\n"; | |
| } | |
| return $buf; | |
| } | |
| use File::fgets; | |
| my $preallocated_str = ''; | |
| vec($preallocated_str, 500, 8) = 0; | |
| $preallocated_str = ''; | |
| #use Devel::Peek; | |
| #Dump($preallocated_str); | |
| # Test an implementation works | |
| #open my($fh), $File; | |
| #my $str; | |
| #while( schwern_alias($fh, 5, $str) ) { | |
| # print $str, "\n"; | |
| #} | |
| cmpthese(shift || -3, { | |
| __control => sub { | |
| open my($fh), $File; | |
| }, | |
| __readline => sub { | |
| open my($fh), $File; | |
| while(my $line = <$fh>) {} | |
| }, | |
| jrandom => sub { | |
| open my($fh), $File; | |
| while( my $line = jrandom($fh, 500) ) {} | |
| }, | |
| schwern => sub { | |
| open my($fh), $File; | |
| while( my $line = schwern($fh, 500) ) {} | |
| }, | |
| schwern_ref => sub { | |
| open my($fh), $File; | |
| while( schwern_ref($fh, 500, \$preallocated_str) ) {} | |
| }, | |
| schwern_alias => sub { | |
| open my($fh), $File; | |
| while( schwern_alias($fh, 500, $preallocated_str) ) {} | |
| }, | |
| fgets => sub { | |
| open my($fh), $File; | |
| while( fgets($fh, 500) ) {} | |
| }, | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment