What is the best way (performance-wise) of returning stl containers from a function? The container returned would usually contain several thousands of items.
Method 1:
typedef std::list<Item> ItemContainer;
ItemContainer CreateManyItems() {
ItemContainer result;
// fill the 'result' ...
return result;
}
ItemContainer a = CreateManyItems();
Method 2:
void CreateManyItems(ItemContainer &output) {
ItemContainer result;
// fill the 'result' ...
output.swap(result);
}
ItemContainer a;
CreateManyItems(a);
Method 3:
void std::auto_ptr<ItemContainer> CreateManyItems() {
std::auto_ptr<ItemContainer> result(new ItemContainer);
// fill the 'result' ...
return result;
}
std::auto_ptr<ItemContainer> a = CreateManyItems();
Or is there any better way?
None: if you just want to fill
std::listwith items, then you can usestd::fillorstd::fill_nor a combination of standard library functions.It’s not clear how exactly you want to fill your list, so I can’t comment on your code precisely. If possible, use the standard library. If you cannot, then go for Method 1, and the compiler may optimize away the return value in your code eliding the unnecessary copies, as most compilers implement RVO.
See these articles on copy elision and return value optimization (RVO):
Related questions:
An article by Dave Abrahams:
I would still emphasize this: have you seen all the generic functions provided by
<algorithm>header? If not, then I would suggest you to first look into them and see if any of them (or a combination of them) can do what you want to do in your code.If you want to create and fill the list, then you can use
std::generate()orstd::generate_nfunction.