Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Index or iterate - your choice

by tobyink (Canon)
on Jan 27, 2021 at 19:46 UTC ( [id://11127531]=note: print w/replies, xml ) Need Help??


in reply to Index or iterate - your choice

Generally speaking, if you want to provide a list of things, just return a list. People can assign it to an array and loop through it, access a particular element by index, etc.

The exceptions would be where there are so many list items or the items are so big, that they would use too much memory to store in an array, so accessing them one by one is better; or if generating each item is relatively expensive (in terms of time, CPU, network activity, etc) so if you can avoid fetching the entire list, that is preferable. In these cases use an iterator instead.

Replies are listed 'Best First'.
Re^2: Index or iterate - your choice
by thomas895 (Deacon) on Jan 27, 2021 at 21:12 UTC

    where there are so many list items or the items are so big, that they would use too much memory to store in an array
    Perhaps tie-ing is another good option for this. Then you can get all the semantics of an array for free! (from the user perspective at least)

    -Thomas
    "Excuse me for butting in, but I'm interrupt-driven..."

      I did consider including that, but by providing a tied array, you're kind of encouraging end users to treat it as any old array.

      So they might not consider that doing something like:

      foreach my $item ( reverse @array ) { ... }

      Is going to impact performance way more than they might expect.

      If it's exposed as an iterator, then it encourages them to access items in a one-at-a-time sequential fashion. They still can slurp it all into an array, but they can't blame you when that eats up all their memory.

      Not saying it's never a good idea, but situations where it is aren't going to be that common.

Re^2: Index or iterate - your choice
by GrandFather (Saint) on Jan 27, 2021 at 21:19 UTC

    After I posted it I wondered if my question was too trivial to post. But it turned out to be a great sanity check! I'm now returning a list as suggested. Thank you, Discipulus and jdporter for shining a spot light on this!

    Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (9)
As of 2024-04-24 08:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found