Skip to content

Instantly share code, notes, and snippets.

@daverigby
Last active August 29, 2015 14:25
Show Gist options
  • Save daverigby/7b672f0d05aa1f6d823e to your computer and use it in GitHub Desktop.
Save daverigby/7b672f0d05aa1f6d823e to your computer and use it in GitHub Desktop.
Compare performance of malloc, new and std::vector::resize().
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char** argv) {
std::string mode(argv[1]);
size_t size(std::stoi(argv[2]));
if (mode == "malloc") {
char* foo = (char*)malloc(size);
} else if (mode == "new") {
char* foo = new char[size];
} else if (mode == "vector") {
std::vector<char> foo;
foo.resize(size);
} else {
std::cerr << "Unknown mode. Valid modes are: malloc, new, vector" << std::endl;
}
}
@daverigby
Copy link
Author

Numbers from Late 2013 MBP (Haswell):

$ /usr/bin/time ./a.out malloc 1000000000
    0.00 real         0.00 user         0.00 sys
$ /usr/bin/time ./a.out new    1000000000
    0.00 real         0.00 user         0.00 sys
$ /usr/bin/time ./a.out vector 1000000000
    2.98 real         2.59 user         0.36 sys

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