Beware context. A quick test:
shows that these blocks are called in void context, and I believe that grep has optimisations in place for that. It would be worth assigning the results to an array to make sure you are actually benchmarking the right thing.perl -MBenchmark=cmpthese -wle 'cmpthese(1, { context => q{print wan +tarray ? "list" : defined(wantarray) ? "scalar" : "void"}})'
However I tried that here, and got similar results to you (the maximum difference being 10%), so I think you can discount permutations of the grep as a source of significant savings and concentrate on whichever version reads best to you.
In the context of the for loop, however, you may be better off losing the grep altogether - writing it as something like:
would avoid the need to copy the list to the stack, which might well be a win for long lists.for my $element (@array) { length($element) or next; ... }
Hugo
In reply to Re: Benchmarking the block and list forms of grep
by hv
in thread Benchmarking the block and list forms of grep
by grinder
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |