Is there a way I can modify your code so that in can incorporate any length of sub-array size?
Not really. The basis of the main gain is the well-known optimisation called Loop unrolling.
As with most optimisations, it relies on trading application specific knowledge for generic programing practices. As soon as you put back the generic loop:
my @sums;
for my $ref ( @data ) {
$sums[ $_ ] += $ref->[ $_ ] for 0 .. $#$ref;
}
$sums[ $_ ] /= @data for 0 .. 3;
You lose most of the gains.
If your application really calls for best speed, but the size of the sub-array can vary from run to run, then using a dynamic language like Perl does offer one possibility not available with non-dynamic languages. That of code generation.
You could eval a sub into existance at runtime that unrolls the loop to deal with the right number of subarray elements for that particular run, giving you the best of both worlds. Genericity and application specific knowledge.
Whether that is worth the extra complexity and maintenance effort will depend upon the specifics of your application. If you really need the performance, it is worth considering.
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
|