One of the more questionable things my file reading modules does is keep a list of opened file handles in a global hash allowing me to perform multiple operations on a filehandle by name. I was benchmarking the write times for syswrite vs PerlIO and I found something very strange, while keeping the file handle open normally results in being an order of magnitude faster on the test where a binmode($fh,':encoding(UTF-8)) is used the rate drops from several thousand to 30 runs a second. It doesn't happen on read operations and it doesn't happen with just binmode($fh) (sans encoding). It's not a huge deal, just validates my decision to make not using PerlIO the default but still, 7700% is a lot of difference for what I would've assumed is the same basic operation. SSSCE and benchmark as follows...
use Benchmark qw/cmpthese timethese/; my (@array,%handle); my $file = 'testout.txt'; for (1 .. 1000) { push @array, 'It was the best of times, it was the w +orst of times...' . $/; } cmpthese(-8, { close => sub { &printfile(@array); }, noclose => sub { &printfile(@array,{noclose=>1}); }, }); sub printfile { my $opts = ( ref $_[-1] eq 'HASH' ) ? pop : {}; my $fh; my $string = join '', @_; if ($handle{$file}) { $fh = $handle{$file}; binmode $fh, ':encoding(UT +F-8)'; } else { open($fh, "> :encoding(UTF-8)", $file) || die "Can't open $file fo +r writing: $!"; $handle{$file} = $fh unless (! $opts->{'noclose'}); } seek($fh, 0, 0); print $fh $string; close $fh unless ($opts->{'noclose'}); }
Benchmark Results
          Rate noclose   close
noclose 29.9/s      --    -99%
close   2330/s   7705%      -- 

In reply to Why is using binmode on a file handle 77 times slower than just closing it and re-opening? by Maelstrom

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.