Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between list and forward_list performance?

As with c++11 we have two types of list:

std::list<int> lst = { 1, 2, 3, 4, 5 };

std::forward_list<int> flst = { 5, 4, 3, 2, 1};

As we know that the list is based on the doubly linked list and forward_list is based on the singly linked list.

How should we decide which one to used? Is there any performance benefit of any of the list above other?

like image 815
Swapnil Avatar asked Aug 25 '18 09:08

Swapnil


1 Answers

How should we decide which one to used?

Decide if you need bidirectional iteration. If forward iteration is good enough, use std::forward_list, unless you need to support C++ versions older than C++11, which may only have std::list.

Is there any performance benefit of any of the list above other?

std::forward_list eliminates a pointer per node (with all the attendant benefits for the data cache and memory subsystem), while std::list provides constant-time iterator decrement.

But in practice, neither of these containers is as widely used as one might believe when attending computer science school. The real performance of std::vector is superior for many applications, and its memory usage is always less. More demanding applications requiring lists would do well to consider intrusive lists, which standard C++ does not provide.

like image 98
John Zwinck Avatar answered Nov 15 '22 07:11

John Zwinck