473,785 Members | 2,249 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 #1
30 4504
Antonios Christofides wrote:
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?
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.
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 ?
Not much.
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.


Jul 22 '05 #2
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.
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?
What would 'realloc' do? Place the objects each at a different memory
location without letting the object know? That's not right. Objects
may need to know where they have been constructed. They might want to
let other classes or objects know of their location, etc.
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 ?
Nope. Using standard containers requires acknowledging the trade-offs.
If you need fast push_back and you don't know the size, you should
probably use 'std::list' or 'std::deque'. If you need random access
afterwards, don't push-back without reserving. I bet any decent book
on Standard containers talks about how to pick the container well-suited
for your task. Of course, that assumes that you know what your task is.
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.


It doesn't matter, at least not here.

V
Jul 22 '05 #3
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.
Do you think you could go to an algorithm where you push less back?
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?


Read Herb Sutter's way-cool GOTW series, and his books /Exceptional C++/. He
impugns the container class of choice should usually be std::deque<>, not
std::vector<>. It frags not memory like std::list<>, and it's optimal to
push things to both the beginning and end.

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces
Jul 22 '05 #4
"Antonios Christofides" <an*****@itia.n tua.gr> wrote in message
news:dc5.4159da 31.d0edf@voltai re...
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.


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.
Jul 22 '05 #5
> 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?
Jul 22 '05 #6
"Method Man" <a@b.c> 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.


You've been reading too many C texts, haven't you?
So why is 'realloc' more efficient?


I am not sure how to answer this question. Imagine you have a tree which
has grown too far up and needs trimming. You decide to trim it a foot off
the ground because it's too inefficient to climb up and trim every branch
that could use a trimming. You lose the tree. Why is cutting it down more
efficient than doing it right? There is no answer. Another analogy: a TV
set and a need to deliver it from the 7th floor to the truck parked outside.
It can be done on an elevator, it could be done on the stairs. Or, somebody
might decide that it's more efficient to lower it down through the window.
Without ropes. Hey, a couple of seconds and it's down on the ground, no?
Why is throwing it down more efficient than using the elevator (or stairs)?

For POD you can do realloc. For non-POD classes (general case) realloc will
simply not work. Efficient or not.

V
Jul 22 '05 #7
"Method Man" <a@b.c> wrote in message news:oJq6d.4788
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?


Because if more space exists at the end of the existing array to yield a
larger array, then realloc will just claim that space. Say you do
malloc(512u) and the program reserves bytes 0x101 to 0x300 for your array.
Say bytes 0x301 to 0x0500 are free for anyone to use. If no other objects
request this space and you realloc the array to 1024u bytes, then the system
may just mark bytes 0x0101 to 0x0500 as in use by your array (so no-one else
can claim it).

There's no garuantee that space is available, but if it is, we save copying
lots of bytes.
Jul 22 '05 #8
"Antonios Christofides" <an*****@itia.n tua.gr> wrote in message
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?
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.
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 ?


What about std::list? What is wrong with std::deque?

If you have a large object, it might be a good idea to make it reference
counted. You can use boost::shared_p tr or the like.
Jul 22 '05 #9

"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:tEr6d.1720 09$3l3.160912@a ttbi_s03...
"Method Man" <a@b.c> 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.


You've been reading too many C texts, haven't you?


Well yea.

I was talking about arrays of POD types, but I didn't make that clear in my
post. Of course non-POD types can have constructors and overloaded
assignment operators, so my question wouldn't make sense in that case.
So why is 'realloc' more efficient?


I am not sure how to answer this question. Imagine you have a tree which
has grown too far up and needs trimming. You decide to trim it a foot off
the ground because it's too inefficient to climb up and trim every branch
that could use a trimming. You lose the tree. Why is cutting it down

more efficient than doing it right? There is no answer. Another analogy: a TV
set and a need to deliver it from the 7th floor to the truck parked outside. It can be done on an elevator, it could be done on the stairs. Or, somebody might decide that it's more efficient to lower it down through the window.
Without ropes. Hey, a couple of seconds and it's down on the ground, no?
Why is throwing it down more efficient than using the elevator (or stairs)?
For POD you can do realloc. For non-POD classes (general case) realloc will simply not work. Efficient or not.


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.
Jul 22 '05 #10

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
4175
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
3226
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
21033
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
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10356
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10161
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
10098
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,...
1
7506
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
6743
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5390
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
5523
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3662
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.