in reply to Re^3: Which, if any, is faster?
in thread Which, if any, is faster?
One way of addressing the array indices problem is to declare constants for your array elements.
use constant { SELF => 0, CODE_TO_RUN => 1, FIRST_DAUGHTER => 0, LAST_DAUGHTER => 1, NEXT_SISTER => 2, PREVIOUS_SISTER => 3, PARENT => 4, }; ## then in your methods sub traverse { if( $_[SELF][FIRST_DAUGHTER] ) { traverse( $_[SELF][FIRST_DAUGHTER], $_[CODE_TO_RUN] ); } elsif( $_[SELF][NEXT_SISTER] ) { traverse( $_[SELF][NEXT_SISTER], $_[CODE_TO_RUN] ); elsif( ... ) ...; } return; }
Constants created this way get turned into constant subroutines which then get optimised away leaving just the value behind which makes for an efficient way of indexing arrays symbolically.
And by using the aliasing of @_ directly, rather than shifting or copying values into lexicals, you save a little more time and space.
With well chosen constant names, it is also eminently readable, even if the uppercase tends to look a little strange at first.
For those methods (like traverse()) that lend themselves to tail recursion, you can take this further:
sub traverse { return unless defined $_[SELF]; $_[CODE_TO_RUN]->( ... ); $_[SELF] = $_[SELF][FIRST_DAUGHTER] || $_[SELF][NEXT_SISTER] || undef; goto &traverse; }
But some might consider that a step too far.
|
|---|