May 2013 Archives

Why you don't need File::Slurp…

#! /usr/bin/env perl

use strict;
use warnings;
use Benchmark 'cmpthese';
use File::Slurp 'read_file';

my $filename = shift or die "No argument given";
my $count = shift || 10;

cmpthese($count, {
    'Unix'  => sub { open my $fh, '<:unix', $filename or die "Couldn't open $filename: $!"; read $fh, my $buffer, -s $fh or die "Couldn't read $filename: $!" },
    'Slurp' => sub { read_file($filename, buffer_ref => \my $buffer, binmode => ':raw') },
});

For large files, it's just as fast as File::Slurp is:

        Rate Slurp  Unix
Slurp 2.28/s    --   -0%
Unix  2.29/s    0%    --

For small files, it's actually significantly faster:

          Rate Slurp  Unix
Slurp  51020/s    --  -66%
Unix  151515/s  197%    --

So why use File::Slurp, when a two-liner will actually perform better?

About Leon Timmermans

user-pic