2 ms·
I would usually choose option 2 or 3, but that is because usually small performance discrepancies are unimportant. If performance is paramount at the point in
by jaawn 11y ago
I would usually choose option 2 or 3, but that is because usually small performance discrepancies are unimportant. If performance is paramount at the point in the code where the library is used, I would opt for (1) or a fourth option you omitted: find a library which has already implemented a performance-driven solution.
It is similar to sorting implementations. If you have a small list of items in a collection, you might not care about how fast they can be sorted as long as it is "reasonably fast," so you can just use a built-in sort() function. If you know your collection will likely be larger than most, or you need them sorted as fast as possible, you might choose to implement your own sorting function, or use a different library which specifies a given performance level.
You could just use this hypothetical, built-in sort() for now, and deal with it later if any issues arise, or you could plan ahead if it is important and future proof the code now. The former would be "proceeding with caution" while the latter would be the more maintainable, "best practices" approach when you know performance is higher priority than normal.
If you "proceed with caution" you might run into a situation where the maintainers switch from insertion sort to heap sort, because in many (most?) use cases, heap sort is faster. However, your collection is often already sorted or mostly sorted, which is a case where heap sort performs much worse than insertion sort. Now your specific application has worse performance, but other applications have improved performance. If your collection needs to be sorted at a specific performance level, it is better (but not required) for you to implement a custom sort function, or use a library that is designed for your use case. This way you can have appropriate control over the performance.