in reply to Perl and common subexpressions

Nice post, Stevie-O. Of course, you already knew I would say that, since we talked about it before you posted... but you know.

I was curious to see when the common subexpression elimination would pay off. So I tested both hashes and arrays against eachother at various depths, to see when the CSE would overcome the assignment overhead. Here's my benchmark (sorry for the cryptic names, I didn't feel like typing a whole lot):

#!/usr/bin/perl use strict; use warnings; use Benchmark qw(cmpthese timethese); my %a; $a{a}{a} = 1; $a{a}{b} = 2; my %b; $b{a}{a}{a} = 1; $b{a}{a}{b} = 2; my %c; $c{a}{a}{a}{a} = 1; $c{a}{a}{a}{b} = 2; my @a; $a[0][0] = 1; $a[0][1] = 2; my @b; $b[0][0][0] = 1; $b[0][0][1] = 2; my @c; $c[0][0][0][0] = 1; $c[0][0][0][1] = 2; cmpthese(-2, { h_c_a => sub { my $c = $a{a}; $c->{a} * $c->{b} }, h_no_c_a => sub { $a{a}{a} * $a{a}{b} }, }); cmpthese(-2, { h_c_b => sub { my $c = $b{a}{a}; $c->{a} * $c->{b} }, h_no_c_b => sub { $b{a}{a}{a} * $b{a}{a}{b} }, }); cmpthese(-2, { h_c_c => sub { my $c = $c{a}{a}{a}; $c->{a} * $c->{b} }, h_no_c_c => sub { $c{a}{a}{a}{a} * $c{a}{a}{a}{b} }, }); cmpthese(-2, { a_c_a => sub { my $c = $a[0]; $c->[0] * $c->[1] }, a_no_c_a => sub { $a[0][0] * $a[0][1] }, }); cmpthese(-2, { a_c_b => sub { my $c = $b[0][0]; $c->[0] * $c->[1] }, a_no_c_b => sub { $b[0][0][0] * $b[0][0][1] }, }); cmpthese(-2, { a_c_c => sub { my $c = $c[0][0][0]; $c->[0] * $c->[1] }, a_no_c_c => sub { $c[0][0][0][0] * $c[0][0][0][1] }, });
$ perl depth.pl Rate h_c_a h_no_c_a h_c_a 674632/s -- -14% h_no_c_a 782184/s 16% -- Rate h_no_c_b h_c_b h_no_c_b 521502/s -- -10% h_c_b 578953/s 11% -- Rate h_no_c_c h_c_c h_no_c_c 376222/s -- -23% h_c_c 490846/s 30% -- Rate a_c_a a_no_c_a a_c_a 964660/s -- -15% a_no_c_a 1129931/s 17% -- Rate a_c_b a_no_c_b a_c_b 718901/s -- -4% a_no_c_b 745514/s 4% -- Rate a_no_c_c a_c_c a_no_c_c 549898/s -- -12% a_c_c 625570/s 14% --

It looks like hashes get a benefit at just 2 levels of references, but with arrays it doesn't pay off until 3 levels. Maybe not very surprising, but possibly useful information.