Re: efficient max() function from sort
[email protected] ("Chas. Owens")
| Newsgroups | perl.beginners |
|---|---|
| Message-ID | <[email protected]> |
On Wed, May 28, 2008 at 5:07 PM, Rob Dixon <[email protected]> wrote: snip > $max = (sort {$a <=> $b} @z)[-1]; snip my $max = (sort { $b <=> $a } @z)[0]; is slightly faster than using [-1]. You should only use this form if performance matters and you know that @z is smaller than 250 items (over 250 items List::Util::max is faster). In general using List::Util::max (or rolling your own with a for loop) is preferable to the sort. You know it will take O(n) time, whereas the sort may take up to O(n*n) time in worst case scenarios and the average case takes O(n log n) time (but happens to be faster for small lists due to the fact that sort is written in C). Of course, if speed matters then you should probably try to find a way to know max values ahead of time anyway. -- Chas. Owens wonkden.net The most important skill a programmer can have is the ability to read.