Skip to content

Instantly share code, notes, and snippets.

@mloskot
Last active December 14, 2015 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mloskot/5160967 to your computer and use it in GitHub Desktop.
Save mloskot/5160967 to your computer and use it in GitHub Desktop.
Is your std::vector<byte>::resize implementation optimal?
// Is your C++11 std::vector<byte>::resize implementation optimal?
//
// Visual C++ 11:
// reserve() -> fill_n -> detail: _Fill_n -> memset:
//
// inline unsigned char *_Fill_n(unsigned char *_Dest, size_t _Count, unsigned char _Val)
// { // copy unsigned char _Val _Count times through [_Dest, ...)
// _CSTD memset(_Dest, _Val, _Count);
// return (_Dest + _Count);
// }
//
#include <chrono>
#include <iostream>
#include <vector>
int main()
{
struct elapsed
{
typedef std::chrono::high_resolution_clock tclock;
typedef std::chrono::milliseconds tunit;
std::chrono::time_point<tclock> start;
elapsed() : start(tclock::now()) {}
~elapsed()
{
std::cout << "elapsed: "
<< std::chrono::duration_cast<tunit>(tclock::now()-start).count()
<< std::endl;
}
};
typedef unsigned char byte_t;
typedef std::vector<byte_t> v_t;
auto p = [](v_t const& v)
{
std::cout << "vector size: " << v.size() << " capacity: " << v.capacity() << std::endl;
};
auto s = 4294967295UL;//4294967295UL;
{
std::cout << "array new: "<< s << std::endl;
byte_t* p = nullptr;
{
elapsed e;
p = new byte_t[s];
}
delete [] p;
}
{
std::cout << "array new with zero-init: "<< s << std::endl;
byte_t* p = nullptr;
{
elapsed e;
p = new byte_t[s]();
}
delete [] p;
}
{
std::cout << "vector reserve: "<< s << std::endl;
elapsed e;
v_t v;
v.reserve(s);
p(v);
}
{
std::cout << "vector construct: "<< s << std::endl;
elapsed e;
v_t v(s);
p(v);
}
{
std::cout << "vector resize: "<< s << std::endl;
v_t v;
p(v);
elapsed e;
v.resize(s);
p(v);
}
return 0;
}
@mloskot
Copy link
Author

mloskot commented Mar 14, 2013

Visual C++ 11 - Release|x64

array new: 4294967295
elapsed: 0
array new with zero-init: 4294967295
elapsed: 2217
vector reserve: 4294967295
vector size: 0 capacity: 4294967295
elapsed: 3
vector construct: 4294967295
vector size: 4294967295 capacity: 4294967295
elapsed: 2629
vector resize: 4294967295
vector size: 0 capacity: 0
vector size: 4294967295 capacity: 4294967295
elapsed: 1952

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment