greping through an array is an O(n) operation, meaning the amount of work being done carries a 1:1 relationship to the amount of data being acted upon. There is no less-costly way of finding all occurrences of some pattern in an array than to actually look at each element in the array to check for the existance of a pattern. No magic here. You could try stirring up a potion of bat wings, lizzard lips and duck poop, and hum an incantation as it boils in a big black pot, but pretty much those days were over a few centuries ago, and nowadays we're stuck with reality.

If this is an operation that you'll be doing frequently on a large and infrequently changing data set, it may be beneficial to presort the string or cache your search results, but that strategy could prove much more costly if your performing the operation relatively infrequently, or on a frequently changing set of data. The theory here is that maybe you could perform a O(n log n) operation once in order to provide O(1) lookups later on. But again, that only makes sense if you are going to be doing enough lookups down the road to justify the costly O(n log n) (or maybe even O(n^2), or worse) operation to begin with, and if you can assure that you won't have to be doing the more costly operation frequently.

The fact is that iterating through a list is not all that epensive, unless you do it a lot. And if you do it a lot, you might need to look at strategies for keeping track of order, or for caching search results.


Dave


In reply to Re^4: Array manipulation by davido
in thread Array manipulation by Chon-Ji

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.