in reply to Re^3: Array manipulation
in thread Array manipulation
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
|
|---|