in reply to Re^2: Open Filehandle once
in thread Open Filehandle once
"Also please do not recommend using map in void context."
In general, I agree with this statement.
"This is considered bad practice by many programmers since you are only making the call for its side-effects whilst throwing away its output."
However, I disagree with this reason.
The issue with "throwing away its output" was resolved, about 14 years ago[perlhist], in Perl 5.8.1. From "perl581delta: Miscellaneous Enhancements":
"map in void context is no longer expensive. map is now context aware, and will not construct a list if called in void context."
The reason I would give for not using map in void context is based on efficiency. I've had reason to benchmark map vs. for on a number of occasions over the years: I've always found for to be measurably faster than map; and, unsurprisingly, map EXPR is faster than map BLOCK.
Here's a very quick and dirty benchmark I just wrote to show this:
#!/usr/bin/env perl use strict; use warnings; use Benchmark 'cmpthese'; my @x = 0 .. 99; cmpthese 1e6 => { map_expr => sub { my @y = @x; map ++$_, @y; return }, map_block => sub { my @y = @x; map { ++$_ } @y; return }, for => sub { my @y = @x; ++$_ for @y; return }, };
I ran this five times. All results were much the same. This one was roughly in the middle:
Rate map_block map_expr for map_block 75019/s -- -44% -47% map_expr 134953/s 80% -- -5% for 141844/s 89% 5% --
Benchmark run using:
$ perl -v | head -2 | tail -1 This is perl 5, version 26, subversion 0 (v5.26.0) built for darwin-th +read-multi-2level
— Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Open Filehandle once
by 1nickt (Canon) on Aug 25, 2017 at 16:53 UTC | |
by kcott (Archbishop) on Aug 26, 2017 at 15:57 UTC | |
|
Re^4: Open Filehandle once
by Anonymous Monk on Aug 25, 2017 at 02:51 UTC |