Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(6925)

Unified Diff: base/strings/string_number_conversions.cc

Issue 1359253003: Optimise IntToString by avoiding string allocation. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Changes proposed by mark. Created 5 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « no previous file | no next file » | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: base/strings/string_number_conversions.cc
diff --git a/base/strings/string_number_conversions.cc b/base/strings/string_number_conversions.cc
index 16d98c8a3e9d4deb4655f75b31e052f2cacf459c..0f4f38133219521f2cd889d80281a88e8619b095 100644
--- a/base/strings/string_number_conversions.cc
+++ b/base/strings/string_number_conversions.cc
@@ -27,30 +27,32 @@ struct IntToStringT {
static STR IntToString(INT value) {
// log10(2) ~= 0.3 bytes needed per bit or per byte log10(2**8) ~= 2.4.
// So round up to allocate 3 output characters per byte, plus 1 for '-'.
- const int kOutputBufSize =
+ const size_t kOutputBufSize =
3 * sizeof(INT) + std::numeric_limits<INT>::is_signed;
- // Allocate the whole string right away, we will right back to front, and
+ // Create the string in a temporary buffer, write it back to front, and
// then return the substr of what we ended up using.
- STR outbuf(kOutputBufSize, 0);
+ using CHR = typename STR::value_type;
+ CHR outbuf[kOutputBufSize];
// The ValueOrDie call below can never fail, because UnsignedAbs is valid
// for all valid inputs.
auto res = CheckedNumeric<INT>(value).UnsignedAbs().ValueOrDie();
- typename STR::iterator it(outbuf.end());
+ CHR* end = outbuf + kOutputBufSize;
+ CHR* i = end;
do {
- --it;
- DCHECK(it != outbuf.begin());
- *it = static_cast<typename STR::value_type>((res % 10) + '0');
+ --i;
+ DCHECK(i != outbuf);
+ *i = static_cast<CHR>((res % 10) + '0');
res /= 10;
} while (res != 0);
if (IsValueNegative(value)) {
- --it;
- DCHECK(it != outbuf.begin());
- *it = static_cast<typename STR::value_type>('-');
+ --i;
+ DCHECK(i != outbuf);
+ *i = static_cast<CHR>('-');
}
- return STR(it, outbuf.end());
+ return STR(i, end);
}
};
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698