Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Processing arrays 2 elements at a time (TIMTOWTDI)

by petral (Curate)
on Aug 02, 2002 at 15:47 UTC ( [id://187132]=note: print w/replies, xml ) Need Help??


in reply to Processing arrays 2 elements at a time (TIMTOWTDI)

    the code that I consider as being the easiest for a non-expert to read is also the fastest

Although, note that it probably would not be the fastest inline:
my @copy = @$r; while( @copy ) { push @$r2, [ shift @copy, shift @copy ]; }
It is only the artifact of using @_ in the sub call which avoids the copy.

  p

Replies are listed 'Best First'.
Re: Re: Processing arrays 2 elements at a time (TIMTOWTDI)
by ichimunki (Priest) on Aug 02, 2002 at 19:38 UTC
    So don't make your copy first. It's a reference after all, which in this case makes life easy.
    my @copy; while (@$r) { push @copy, [ shift @$r, shift @$r ]; } $r = \@copy;
    This way we build our new array (while the one gets bigger, the other gets smaller), then we simply change what the reference points to.
      That's very neat.   My only point was that the way grinder was presenting it (non-destructive of the original array), it would probably not be the fastest if the array copy was not hidden in the overhead for the subroutine call.

        p
        I'm sorry. I guess I thought his requirements didn't preclude a destructive routine, since he opens with $r = [1,2,3,4,5,6] and wants to replace that with $r = [[1,2],[3,4],[5,6]] and both the shifter and splicer techniques in the benchmark are destructive. My money's on the c-loop for non-destructive, and if I had large tuples or frequently changing tuple lengths, I'd use splicer in spite of the speed hit shown here.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://187132]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2024-03-29 00:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found