JSON: Improve json::decode() performance

- Improves "load" time by ~28% across all performance tests.
- Improves the "add" performance test by ~20% since "load" takes most
  of the time there.
This commit is contained in:
Wilhelm Schuermann
2015-10-24 10:47:34 +02:00
parent 84c85b7596
commit f4ba6015a8

View File

@@ -405,38 +405,45 @@ std::string json::encode (const std::string& input)
std::string json::decode (const std::string& input) std::string json::decode (const std::string& input)
{ {
std::string output; std::string output;
for (unsigned int i = 0; i < input.length (); ++i) size_t pos = 0;
while (pos < input.length ())
{ {
if (input[i] == '\\') if (input[pos] == '\\')
{ {
++i; ++pos;
switch (input[i]) switch (input[pos])
{ {
// Simple translations. // Simple translations.
case '"': output += '"'; break; case '"': output += '"'; break;
case '\\': output += '\\'; break; case '\\': output += '\\'; break;
case '/': output += '/'; break; case '/': output += '/'; break;
case 'b': output += '\b'; break; case 'b': output += '\b'; break;
case 'f': output += '\f'; break; case 'f': output += '\f'; break;
case 'n': output += '\n'; break; case 'n': output += '\n'; break;
case 'r': output += '\r'; break; case 'r': output += '\r'; break;
case 't': output += '\t'; break; case 't': output += '\t'; break;
// Compose a UTF8 unicode character. // Compose a UTF8 unicode character.
case 'u': case 'u':
output += utf8_character (utf8_codepoint (input.substr (++i))); output += utf8_character (utf8_codepoint (input.substr (++pos)));
i += 3; pos += 3;
break; break;
// If it is an unrecognized sequence, do nothing. // If it is an unrecognized sequence, do nothing.
default: default:
output += '\\'; output += '\\';
output += input[i]; output += input[pos];
break; break;
} }
++pos;
} }
else else
output += input[i]; {
size_t next_backslash = input.find ('\\', pos);
output.append (input, pos, next_backslash - pos);
pos = next_backslash;
}
} }
return output; return output;