Says merlyn:
using sort to get the minimum value is far more expensive than it needs to be.
While that's true, I think people overestimate the cost.
For small lists, say up to a thousand items, it probably
doesn't make much of a difference. It's like paying seven cents for a five cent candy bar.
On the one hand, you're being overcharged by 40%.
But a more useful way to look at it may be that you don't
care because it's only two cents.
For another take on this,
see here and here, for example.
| [reply] |
Good point. For most usage the difference between a log
factor and a constant is pretty much a non-issue. Sure
theoretically a log factor will eventually dwarf any
constant in the end, but in practice it doesn't tend to
work that way.
The general rule of thumb is that an exponential performance
issue keeps your program from running, a quadratic one
will work fine but keeps you from scaling well, and
a logarithmic one is about as big a deal as a poor constant.
(And yes, I know Dominus knows all this. This is for
everyone else's benefit.)
| [reply] |
While this is true, and I agree with your POV, if I'm writing something that I'm not 100% sure how it will be used in the future, I subconsciously avoid potentially expensive methods where there is a better alternative. Sure, it probably doesn't mean much in the end, but it might some day...
update: I should qualify this a bit further by saying that in cases where performance really doesn't matter with the level of usage and data I'm working with, readability and maintainability become the overriding concern, so yah I will on occasion go with a slightly less efficient method if it's significantly more readable, but generally my optimizations are almost subconscious when I'm coding. I would almost go with something in List::Util rather than sort to find a minimum, unless I were working towards a one-liner.
| [reply] |