简体   繁体   中英

std::vector and std::list find_if and max_element performance

I am confused about performance of my code tested for std::vector and std::list . Is there a difference between these two when it comes to find_if and max_element ?

In terms of big-O notation, both have identical performance of O(n). ( find_if can be less if the element is found sooner, but this is equally true for both containers.)

In terms of actual wall-clock time, the vector will perform better due to cache coherency; all the vector elements are sequential in memory, so accessing them will make better use of the CPU cache. A linked list's elements can be scattered throughout memory, and you also need to follow the list links which takes time.

Both algorithms are O(n) in terms of computational complexity, but vectors allocate their elements in a contiguous region of storage, which will most likely result in a higher cache hit rate. Traversing a lists, on the other hand, involves a scattered memory access pattern that is likelier to result in a higher rate of cache misses.

As always when it comes to performance, anyway, do measurements before making decisions.

For max_element, all elements of both list and array will be traversed. So, both are O(n) in terms of performance.

Again for find_if, the traversal will be linear (O(n)) for both the data structures.

I don't think there should not much of a difference apart from the constants relative to each.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM