Re: What is the output of this program?
* kanze:
Earl Purple wrote:
Alf P. Steinbach wrote:
push_back can be a tad inefficient on strings, because
strings are usually short, and for short sequences the
reallocations, assuming scaling of buffer size, are more
frequent and thus more costly.
I don't think it's the allocations that make push_back
inefficient, (you can do reserve() ahead and std::string will
often allocate enough anyway). What makes it inefficient is
that push_back has to do a bounds-check on every call (how
else will it know whether to reallocate?).
Much more efficient is resize().
I doubt it. I also doubt that either make a significant
difference.
Possibly you're talking about something entirely different than the
following program?
<code>
#include <cstddef> // std::size_t, EXIT_SUCCESS, EXIT_FAILURE
#include <ctime> // std::clock, std::clock_t
#include <iostream> // std::cout, std::cerr
#include <ostream> // operator<<, std::endl
#include <stdexcept> // std::exception
#include <string> // std::string
std::size_t const nIterations = 100000;
std::size_t const nCharsToAdd = 100;
void pushbacking( std::string& s )
{
for( std::size_t i = 0; i < ::nCharsToAdd; ++i )
{
s.push_back( '*' );
}
}
void indexing( std::string& s )
{
std::size_t const originalSize = s.size();
s.resize( originalSize + nCharsToAdd );
for( std::size_t i = originalSize; i < originalSize +
::nCharsToAdd; ++i )
{
s[i] = '*';
}
}
void test( std::string const& fName, void f( std::string& ) )
{
std::clock_t const startTime = std::clock();
for( std::size_t i = 1; i <= ::nIterations; ++i )
{
std::string s = "knurre, voff!";
f( s );
}
std::clock_t const endTime = std::clock();
double const duration =
double(endTime - startTime)/CLOCKS_PER_SEC;
std::cout << fName << ": " << duration << " seconds." << std::endl;
}
#define TEST( f ) test( #f, f )
void cppMain()
{
TEST( pushbacking );
TEST( indexing );
}
int main()
{
try
{
cppMain();
return EXIT_SUCCESS;
}
catch( std::exception const& x )
{
std::cerr << "!" << x.what() << std::endl;
return EXIT_FAILURE;
}
}
</code>
With two different compilers on my clunky old home PC:
* MSVC 7.1:
pushbacking: 1.468 seconds
indexing: 0.125 seconds.
* g++ 3.4.4:
pushbacking: 10.344 seconds.
indexing: 0.313 seconds.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]