Move heap-based objects like vectors and strings outside the parse loop in LoadObjWithCallback().

This avoids reallocation on every use making the code faster.
This commit is contained in:
Adi Shavit @ MacBookPro
2016-07-27 10:00:13 +03:00
parent d496d8eab6
commit 0b0bf60137

View File

@@ -1317,8 +1317,15 @@ bool LoadObjWithCallback(void *user_data, const callback_t &callback,
std::map<std::string, int> material_map;
int material_id = -1; // -1 = invalid
while (inStream->peek() != -1) {
std::vector<index_t> indices;
std::vector<material_t> materials;
std::vector<std::string> names;
names.reserve(2);
std::string name;
std::vector<const char *> names_out;
std::string linebuf;
while (inStream->peek() != -1) {
std::getline(*inStream, linebuf);
// Trim newline '\r\n' or '\n'
@@ -1383,7 +1390,7 @@ bool LoadObjWithCallback(void *user_data, const callback_t &callback,
token += 2;
token += strspn(token, " \t");
std::vector<index_t> indices;
indices.clear();
while (!IS_NEW_LINE(token[0])) {
vertex_index vi = parseRawTriple(&token);
@@ -1443,7 +1450,7 @@ bool LoadObjWithCallback(void *user_data, const callback_t &callback,
#endif
std::string err_mtl;
std::vector<material_t> materials;
materials.clear();
bool ok = (*readMatFn)(namebuf, &materials, &material_map, &err_mtl);
if (err) {
(*err) += err_mtl;
@@ -1463,8 +1470,7 @@ bool LoadObjWithCallback(void *user_data, const callback_t &callback,
// group name
if (token[0] == 'g' && IS_SPACE((token[1]))) {
std::vector<std::string> names;
names.reserve(2);
names.clear();
while (!IS_NEW_LINE(token[0])) {
std::string str = parseString(&token);
@@ -1474,23 +1480,22 @@ bool LoadObjWithCallback(void *user_data, const callback_t &callback,
assert(names.size() > 0);
std::string name;
// names[0] must be 'g', so skip the 0th element.
if (names.size() > 1) {
name = names[1];
} else {
name = "";
name.clear();
}
if (callback.group_cb) {
if (names.size() > 1) {
// create const char* array.
std::vector<const char *> tmp(names.size() - 1);
for (size_t j = 0; j < tmp.size(); j++) {
tmp[j] = names[j + 1].c_str();
names_out.resize(names.size() - 1);
for (size_t j = 0; j < names_out.size(); j++) {
names_out[j] = names[j + 1].c_str();
}
callback.group_cb(user_data, &tmp.at(0),
static_cast<int>(tmp.size()));
callback.group_cb(user_data, &names_out.at(0),
static_cast<int>(names_out.size()));
} else {
callback.group_cb(user_data, NULL, 0);