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?
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();
@BjörnPollex Yes! I forgot to mention that.
std::vector always has its buffer allocated on heap. So regardless of where the vector itself is allocated resizing it will only affect the heap.
None: if you just want to fill std::list
with items, then you can use std::fill
or std::fill_n
or 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()
or std::generate_n
function.
I usually use method 4 (almost identical to method 2):
void fill(ItemContainer& result) {
// fill the 'result'
}
ItemContainer a;
fill(a);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With