string format0(const char* format, va_list ap) {
string str;
char* pBuf = (char*)malloc(102400);
if (pBuf != NULL) {
vsnprintf(pBuf, 102400, format, ap);
str = string(pBuf);
free(pBuf);
}
return str;
}
和
string format1(cstArrChar format, va_list vl) {
char charArr[102400] = {};
vsnprintf(charArr, 102400, format, vl);
return string(charArr);
}
一个分配在堆上面,一个在栈上面,到底哪种写法比较好呢?
方案推荐指数:1
无profiler不要谈效率!尤其在这个云计算、虚拟机、模拟器、CUDA、多核 、多级cache、指令流水线、多种存储介质、……满天飞的时代!
方案推荐指数:29
// mystring struct mystring : std::string { // format void format(const char* formatstr, ...) /*throw(std::bad_alloc)*/ { constexpr size_t BASE_BUFFER_SIZE = 4096; constexpr size_t STEP = 16; char fixed_buffer[BASE_BUFFER_SIZE]; auto buf_len = BASE_BUFFER_SIZE; auto buf = fixed_buffer; va_list vArgList; va_start(vArgList, formatstr); while (true) { auto len = std::vsnprintf(buf, buf_len, formatstr, vArgList); if (len >= 0) { this->assign(buf, static_cast<size_t>(len)); break; } else { if (buf != fixed_buffer) std::free(buf); if (!(buf = reinterpret_cast<char*>(std::malloc(buf_len *= STEP)))) { throw(std::bad_alloc()); } } } va_end(vArgList); if (buf != fixed_buffer) std::free(buf); } }; int main() { try { mystring str; str.format("ABCD == 0x%p --> %ld", &str, 987654321l); std::printf("%s\r\n", str.c_str()); } catch (const std::exception& exp) { std::printf("%s\r\n", exp.what()); } return 0; }
就多几行代码, 增加易用性.何乐而不为