Skip to content

Instantly share code, notes, and snippets.

@pmakholm
Created June 20, 2013 09:35
Show Gist options
  • Save pmakholm/5821490 to your computer and use it in GitHub Desktop.
Save pmakholm/5821490 to your computer and use it in GitHub Desktop.
Benchmark of listing files in directory in perl: ls vs glob vs readdir
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw(cmpthese);
qx(ls -1U); # Populate dir cache
cmpthese(1000, {
'ls-1 (readline)' => sub { open my $fh, "-|", "ls -1"; my @result = <$fh>; },
'ls-1U (readline)' => sub { open my $fh, "-|", "ls -1U"; my @result = <$fh>; },
'ls-1 (split)' => sub { my $result = qx(ls -1); my @result = split /\n/, $result; },
'ls-1U (split)' => sub { my $result = qx(ls -1U); my @result = split /\n/, $result; },
'glob' => sub { my @result = glob("*"); },
'readdir' => sub { opendir(my $dh, "."); my @result = readdir($dh); },
});
@pmakholm
Copy link
Author

Example output:

                   Rate glob ls-1 (readline) ls-1 (split) ls-1U (readline) ls-1U (split) readdir
glob             97.4/s   --            -32%         -38%             -46%          -59%    -84%
ls-1 (readline)   143/s  47%              --          -9%             -21%          -40%    -76%
ls-1 (split)      156/s  60%              9%           --             -13%          -34%    -74%
ls-1U (readline)  180/s  85%             26%          15%               --          -24%    -70%
ls-1U (split)     238/s 145%             67%          53%              32%            --    -60%
readdir           592/s 508%            315%         279%             228%          149%      --

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment