A couple of people have benchmarked constant arrays in this thread, but they've both made the same mistake: not checking what their code is doing and thus drawing bad conclusions.
The problem is that this use constant ARRAY => qw(Title Section Subsection Class Category Degree Attempt CountOfCounts);; does not create an array.
It creates a subroutine which returns an array as a list; which accounts for the inefficiency.
On the other hand: This use constant ARRAY => [ qw(Title Section Subsection Class Category Degree Attempt CountOfCounts) ];; creates a subroutine that return a reference to the array, which you can then index efficiently (especially if you use enum for the indexes):
use constant ARRAY => [ qw(Title Section Subsection Class Category Deg +ree Attempt CountOfCounts) ];; use enum = qw(Title Section Subsection Class Category Degree Attempt C +ountOfCounts);; @array = qw(Title Section Subsection Class Category Degree Attempt Cou +ntOfCounts);; cmpthese -1, { var => q[ for(1..1e6){ my $l = $array[ $category ]; } ], const => q[ for(1..1e6){ my $l = ARRAY->[ $category ]; } ], constenum => q[ for(1..1e6){ my $l = ARRAY->[ Category ]; } ], };; Rate var const constenum var 4.57/s -- -1% -18% const 4.64/s 1% -- -17% constenum 5.57/s 22% 20% --
In reply to Re: 'constant' vs array (Ignore bad benchmarks: [mod://constant] arrays are (a little) faster!)
by BrowserUk
in thread 'constant' vs array
by fionbarr
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |