473,796 Members | 2,645 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

vector::push_ba ck performance

Hi,

As I read in the archives, the performance problem caused by memory
reallocations during vector::push_ba ck is a common one. My first C++
program is suffering from it: 300 thousand push_backs result,
according to the profiler, in 20 reallocations; these 20 reallocations
account for 3.6 seconds (Celeron 1.3G), which is 40% of total
execution time.

What I don't understand: why is the reallocation code so complex? I
studied the library source and I have a hard time understanding it,
but it seems to be copying the vector item by item in each
reallocation. Why wouldn't a "realloc" suffice?

And, given that I don't know the vector size beforehand, is there
anything else I can do other than trying deqeue or a guessed
vector::reserve ?

In case it matters, I'm using gcc 3.3 with its standard c++ library on
a Debian sarge, but portability is also an issue.

Thanks!
Jul 22 '05
30 4505
> > All the texts I have read state that, when a dynamic array needs
to be extended, it is better/faster to 'realloc' instead of
creating a new array and copying the elements manually.

So why is 'realloc' more efficient?


Except for what was already said, I believe that even in the cases
when realloc needs to allocate a new memory block rather than extend
the existing one, it uses memmove or some similar operation which will
be faster than manually copying the elements if its implementation
uses specialized mass-byte-copying CPU instructions.
Jul 22 '05 #11

"Andrew Koenig" <ar*@acm.org> skrev i melding
news:do******** *************@b gtnsc04-news.ops.worldn et.att.net...

I'm skeptical.

Here's a little program:

#include <vector>

int main()
{
std::vector<int > v;
for (std::vector<in t>::size_type i = 0; i != 1000000; ++i)
v.push_back(i);
return 0;
}

When I run this program on my machine (admittedly faster than 1.3G, but no
more than twice as fast), it runs in three *hundredths* of a second. And it calls push_back a million times, not 300,000 times.

This behavior suggests to me that your vector must contain objects of a
class that is much more expensive to copy than int.

So I think we need to see more information about your program in order to
understand the source of the performance problem.


How do you time your execution time? Is there _one_ way to time this, or
might your method differ from the OP method?

- Magnus
Jul 22 '05 #12
Siemel Naran wrote:
For user types, especially those managing dynamic memory like
std::string or std::deque, we have to call the overloaded copy
constructor or operator= to the copy.


Thank you for your responses. The contained type is indeed a class
that contains, among other things, a string and another user-class
object. I'll go back to Stroustrup to re-read about shallow and deep
copies and copy constructors and so on, and I'll come back either to
summarize or to ask more questions (the latter seems more likely :-)
Jul 22 '05 #13
Victor Bazarov wrote:
Antonios Christofides wrote:
As I read in the archives, the performance problem caused by memory
reallocations during vector::push_ba ck is a common one. My first C++
program is suffering from it: 300 thousand push_backs result,
according to the profiler, in 20 reallocations; these 20 reallocations
account for 3.6 seconds (Celeron 1.3G), which is 40% of total
execution time.


Three hundred thousand push_backs into a vector without reserve? Seems
unjustified.


From all we know, the number of elements could be between 1 and 30 Million.
After all, the OP said he doesn't know the number of elements beforehand.
So how much would you reserve?

Jul 22 '05 #14
Method Man wrote:
That's what a "realloc" does, too. You usually can't easily make an
already allocated memory block bigger (what would you do with data after
it?), so a new block must be allocated and the data be copied over to it,
then the old one destroyed.


All the texts I have read state that, when a dynamic array needs to be
extended, it is better/faster to 'realloc' instead of creating a new array
and copying the elements manually.

So why is 'realloc' more efficient?


It might just behave like push_back() and allocate more memory than
requested so that the next realloc doesn't need to copy the data to a new
block.

Jul 22 '05 #15
Method Man wrote:
[...]
Your analogies didn't really help in my understanding of realloc.
They were intended to show the pitfalls of using 'realloc' with generic
types. Since now we're talking specifically POD, they are moot.
I was
looking for something like -- 'realloc' is never/sometimes/always more
efficient than malloc'ing a new array and manually copying from the old
array (of PODs). Then justify the choice.


'realloc' works in an implementation-defined way. There is always some
possibility that a memory block allocated for an array can be simply
extended without the need to copy. There is always some possibility
that mere calling malloc and then some kind of copying (even memcpy)
can be less efficient when it's done from within your code than if it
is done in the library written (and optimised) specifically for your
hardware. So, in general 'realloc' will _always_ be at least as fast
as you can emulate it with your own 'malloc' and 'memcpy'.

More on C standard library - in comp.lang.c.

Victor
Jul 22 '05 #16

"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:gu******** *******@newsrea d1.dllstx09.us. to.verio.net...
Method Man wrote:
[...]
Your analogies didn't really help in my understanding of realloc.


They were intended to show the pitfalls of using 'realloc' with generic
types. Since now we're talking specifically POD, they are moot.


Aah, but elsewhere in this thread to OP informs us that in fact he is
dealing with a user defined class. so your analogies were very apt.

Jeff F

Jul 22 '05 #17
Method Man wrote:
All the texts I have read state that, when a dynamic array needs to be
extended, it is better/faster to 'realloc' instead of creating a new array
and copying the elements manually.

So why is 'realloc' more efficient?

Regarding vector, nowhere is required that all elements are copied in a
new location after some vector::push_ba ck(), vector::resize( ) or some
other modifier. In all these case, an operation similar to realloc() is
assumed.
However, as with realloc(), objects may be moved.

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #18
Method Man wrote:
Your analogies didn't really help in my understanding of realloc. I was
looking for something like -- 'realloc' is never/sometimes/always more
efficient than malloc'ing a new array and manually copying from the old
array (of PODs). Then justify the choice.

As Victor said in a follow-up message,

"So, in general 'realloc' will _always_ be at least as fast as you can
emulate it with your own 'malloc' and 'memcpy'."
However your messages are not comprehensible. I haven't understood
exactly what you want to learn since the beginning of this thread.

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #19
> How do you time your execution time? Is there _one_ way to time this, or
might your method differ from the OP method?


A factor of 100 difference? Hardly likely.

Try the program yourself and see.

On my machine it runs so fast that I don't even have time to get my finger
off the enter button before it finishes.
Jul 22 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
9803
by: Hitesh Bhatiya | last post by:
Hi all, I have written a small program to accept some socket connections, which are then added to a vector (using push_back). But after a few calls to the push_back function, it deleted the object that was added last. Could someone please tell me why this happens ? Am I doing something wrong here ?
17
4178
by: Mark P | last post by:
Say I have objects of class C which are fairly large. Then consider: vector<C> vc; vc.push_back(C()); Naively this would seem to construct a temporary object C(), copy it into the space owned by the vector, and then delete the temporary object. I realize this is implementation dependent, but will most modern compilers optimize away the creation of the temporary object, or is
4
1578
by: whocares | last post by:
hi everyone. i'm currently experiencing a strange problem under vc++ 2005 express. i hope someone has a hint for me, i'm kind of lost atm. i'm using a vectors of pointers in my code. using the release build i can add and remove elements aslong as i stay below a certain vector size (13 in this case, no joke). as soon as the vector tries to add element 14 i get a runtime error.
3
3227
by: Al | last post by:
What is the problem with this code? It always crashes at the 'push_back'. I found that thanks to debugging. Any Ideas? Other question: what is a faster way to convert a string to an integer? Is there a built-in function to do that? Here's the code: #include <iostream> #include <fstream> #include <vector> #include <string>
8
1829
by: ma740988 | last post by:
Consider the source snippet int main() { std::vector<double> vec_push( 0x10 ); size_t const SZ = vec_push.size(); std::cout << vec_push.size() << std::endl; if ( SZ != 0x10 ) { cout << " something's amiss " << endl;
6
21036
by: Siam | last post by:
Hi, I'm a little new to stl so bear with me...Say I have the following code: vector<intvec; int i = 3; vec.push_back(i); i=4; cout<<vec.at(0)<<endl;
6
11617
by: jmsanchezdiaz | last post by:
CPP question: if i had a struct like "struct str { int a; int b };" and a vector "std::vector < str test;" and wanted to push_back a struct, would i have to define the struct, fill it, and then push_back it, or could i pushback the two ints directly somehow? Thanks for all.
0
9533
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10239
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10190
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10019
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9057
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7555
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5447
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5579
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2928
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.