본문으로 건너뛰기
Folly Code Review · 29/89

folly Conv 성능 비교 — sprintf·stringstream 대비

· Hawk · 3분 읽기

#한 줄 요약

folly::tosprintf보다 약 5배, stringstream보다 약 15배 빠르다. 비결은 2-digit lookup table, SWAR 8-digit parse, if constexpr dispatch로 런타임 분기 제거다.

#동기

server에서 integer ↔ string은 매 요청 수십 번 발생한다. RPC ID, log line, query string, JSON 숫자, metric counter. 하나당 100 ns만 차이 나도 throughput 5-10% 차이로 환산된다.

1억 req/s 클러스터에서 변환 한 번이 200 ns냐 30 ns냐만 달라져도, 약 170 ns × 100M = 17초의 CPU 시간 차이가 난다. 이 규모에서 stringstream은 사실상 사용 금지다.

#benchmark — int → string

benchmark: convert uint32_t to string (1e6 iter, single thread)
folly::to<std::string> 22 ns/op
fmt::format("{}") 32 ns/op
absl::StrCat 26 ns/op
std::to_string 65 ns/op
snprintf("%u") 110 ns/op
std::ostringstream 450 ns/op
folly::toAppend (no alloc) 9 ns/op (in-place)

folly::tostd::to_string 대비 3배, snprintf 대비 5배, ostringstream 대비 20배. toAppend(buffer 재사용)는 더 빠르다.

#benchmark — string → int

benchmark: parse uint64_t from string (length 1-19, 1e6 iter)
folly::to<uint64_t> 12 ns/op
std::from_chars 14 ns/op
absl::SimpleAtoi 13 ns/op
std::stoull 42 ns/op (throw on fail)
strtoull 25 ns/op
std::istringstream(>>) 390 ns/op

std::from_chars(C++17)와 거의 동등. stoull은 throw가 hot path 분기를 비싸게 만들고, istringstream은 locale·rdbuf 비용으로 30배 느리다.

#내부 구현 — 왜 빠른가

#1. 2-digit lookup table itoa

// 약식
constexpr char gDigitTable[200] =
"00010203040506070809"
"10111213141516171819"
"20212223242526272829"
"30313233343536373839"
"40414243444546474849"
"50515253545556575859"
"60616263646566676869"
"70717273747576777879"
"80818283848586878889"
"90919293949596979899";
uint32_t u64_to_ascii(char* buf, uint64_t v) {
char* p = buf + max_digits;
while (v >= 100) {
auto idx = (v % 100) * 2;
p -= 2;
p[0] = gDigitTable[idx];
p[1] = gDigitTable[idx + 1];
v /= 100;
}
// 1-2 자리 마무리
if (v >= 10) {
auto idx = v * 2;
p -= 2; p[0] = gDigitTable[idx]; p[1] = gDigitTable[idx + 1];
} else {
p -= 1; *p = '0' + v;
}
// ...
}

10진수 division을 2자리씩 하면 한 division으로 두 character. std::to_string은 character 하나씩 처리한다.

#2. SWAR 8-digit atoi

// 약식 — 8 자리 정수 한 번에
uint64_t parse8(const char* s) {
uint64_t w;
std::memcpy(&w, s, 8);
w -= 0x3030303030303030ULL; // '0' 빼기
// multiply chain — 2자리, 4자리, 8자리 결합
w = (w * 10 + (w >> 8)) & 0x00FF00FF00FF00FF;
w = (w * 100 + (w >> 16)) & 0x0000FFFF0000FFFF;
w = (w * 10000 + (w >> 32)) & 0x00000000FFFFFFFF;
return w;
}

이 코드는 32-bit 곱셈 3번으로 8 자리 정수를 만든다. character 단위 ASCII 검사·*10+digit 루프 대신.

#3. if constexpr dispatch

// 약식
template <class Tgt>
Tgt to(StringPiece sp) {
if constexpr (std::is_integral_v<Tgt>) {
return detail::digitsToInteger<Tgt>(sp); // SWAR
} else if constexpr (std::is_floating_point_v<Tgt>) {
return detail::strToFp<Tgt>(sp);
} else if constexpr (is_string_v<Tgt>) {
return Tgt{sp.data(), sp.size()};
} else {
Tgt out;
parseTo(sp, out);
return out;
}
}

분기가 모두 컴파일 타임. virtual call, function pointer 없음. 인라인 가능성이 높아진다.

#다른 라이브러리는 왜 느린가

#sprintf

  • locale lookup (LC_NUMERIC)
  • format string parsing (런타임)
  • variadic argument 처리 (va_list)
  • 모든 conversion specifier 지원 (% 처리)

대부분 unused지만 비용은 항상 지불한다.

#stringstream

  • ios 상태 관리 (precision, fill, width, locale)
  • streambuf 가상 호출
  • sentry 생성/소멸
  • error flag 갱신

OOP overhead가 누적된다. 한 conversion에 virtual dispatch가 5-6번 일어난다.

#std::to_string

  • snprintf wrapper (libstdc++/libc++)
  • 그래서 sprintf와 같은 비용

#메모리 효율

folly::to<std::string>(...)는 모든 인자의 size를 미리 계산해 reserve 한다. realloc 0회.

// 약식
std::string out;
size_t total = estimateSpaceNeeded(a)
+ estimateSpaceNeeded(b)
+ estimateSpaceNeeded(c);
out.reserve(total);
toAppend(a, &out); // no realloc
toAppend(b, &out);
toAppend(c, &out);

absl::StrCat도 같은 전략. std::ostringstream은 매 <<마다 internal buffer를 grow.

#코드 리뷰 포인트

// Bad — hot path에서 매번 std::string 생성
for (auto& metric : metrics) {
log << folly::to<std::string>(metric.id, ":", metric.value, "\n");
}
// Good — buffer 재사용
std::string line;
for (auto& metric : metrics) {
line.clear();
folly::toAppend(metric.id, ":", metric.value, "\n", &line);
log << line;
}

루프 안에서 buffer 재사용으로 할당 0회. 큰 log writer가 이 패턴.

// Bad — float 출력에 std::to_string
std::string s = std::to_string(3.14159); // "3.141590"
// "%f" default — locale에 따라 ','로 출력될 수 있다
// Good — folly 또는 fmt
auto s2 = folly::to<std::string>(3.14159); // locale 비의존
auto s3 = fmt::format("{}", 3.14159);

float은 정확도와 locale 둘 다 문제. folly::to / fmt::format는 Ryu/Grisu를 사용해 최단·정확 표현.

#안티패턴

  • stringstream을 log 한 줄 만드는데 사용: 매 줄 450 ns. fbcode에서는 사실상 금지 사항.
  • to<std::string>을 반복 호출 후 +=: 임시 string과 reallocation 누적. toAppend를 한 buffer에 누적.
  • to<int>로 외부 입력 parse, exception을 정상 흐름으로 처리: throw 비율이 높으면 100배 느려진다. tryTo로.

#정리

  • folly::to는 lookup table + SWAR + if constexpr 조합으로 sprintf 대비 5배, stringstream 대비 15-20배.
  • std::from_chars와 거의 동등한 속도지만 high-level API.
  • toAppend로 buffer 재사용 시 할당 0회.
  • float은 Ryu/Grisu 기반, locale 비의존.
  • hot path는 buffer-reuse + tryTo 패턴이 정답.

#다음 편

Part 7로 넘어가 F14 hash map family를 본다. 먼저 F14ValueMap과 std::unordered_map의 차이.

#관련 항목

Folly Code Review · 30 of 89

  1. 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
  2. 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
  3. 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
  4. 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
  5. 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
  6. 6 Folly production validation 문화 — peta-scale에서 단련된 코드
  7. 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
  8. 8 folly::Promise·makeFuture — Future를 만드는 두 길
  9. 9 folly::SemiFuture vs Future — executor binding의 명시화
  10. 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
  11. 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
  12. 12 folly::Future retry·window·via — 제어 흐름 조합자
  13. 13 folly::fibers 분석 — M:N stackful coroutine
  14. 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
  15. 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
  16. 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
  17. 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
  18. 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
  19. 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
  20. 20 folly::IOBufQueue — chain의 push/pull 추상화
  21. 21 folly::io::Cursor·RWCursor — chain 위의 stream
  22. 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
  23. 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
  24. 24 folly::FBString 분석 — SSO + COW 구현
  25. 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
  26. 26 folly::StringPiece — string_view 호환 분석
  27. 27 folly Join·Split utilities — 문자열 분해와 결합
  28. 28 folly::to·tryTo — text↔num 변환 분석
  29. 29 folly Conv Customization — 사용자 타입 지원
  30. 30 folly Conv 성능 비교 — sprintf·stringstream 대비
  31. 31 folly::F14ValueMap vs std::unordered_map
  32. 32 folly::F14NodeMap — stable pointer가 필요할 때
  33. 33 folly::F14VectorMap — cache-friendly iteration
  34. 34 folly::F14FastMap — auto-select 동작
  35. 35 folly F14 internals — SIMD probing 메커니즘
  36. 36 folly::small_vector — inline storage 분석
  37. 37 folly::FixedString — compile-time string
  38. 38 folly::AtomicHashMap — lock-free read 분석
  39. 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
  40. 40 folly::EvictingCacheMap — LRU 구현 분석
  41. 41 folly::Synchronized — lock wrapper 패턴
  42. 42 folly::SharedMutex 분석
  43. 43 folly::Baton — one-shot wait 동기화
  44. 44 folly::RWSpinLock 분석
  45. 45 folly::PicoSpinLock — 1-byte spinlock
  46. 46 folly::ProducerConsumerQueue — SPSC 큐 분석
  47. 47 folly::MPMCQueue — multi-producer multi-consumer
  48. 48 folly::UnboundedQueue — 동적 크기 lock-free
  49. 49 folly::fibers::Channel — Go-like channel
  50. 50 folly::dynamic — JSON-like dynamic type 분석
  51. 51 folly JSON conversion — toJson·parseJson
  52. 52 folly dynamic ↔ struct — manual marshaling
  53. 53 folly dynamic Visitor pattern — type별 분기
  54. 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
  55. 55 folly::SingletonVault 분석 — 등록·소멸·의존성
  56. 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
  57. 57 folly::ExceptionWrapper — type-erased exception holder
  58. 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
  59. 59 folly::Optional vs std::optional
  60. 60 folly::Function vs std::function
  61. 61 folly::Lazy — 지연 초기화 wrapper
  62. 62 folly Meta 스타일 code review 패턴
  63. 63 folly anti-patterns — 잘못 쓰면 std보다 느림
  64. 64 folly vs std 선택 기준 분석
  65. 65 folly::coro 개요 — production C++20 코루틴 어댑터
  66. 66 folly::coro::Task — lazy single-shot 코루틴
  67. 67 folly::coro::AsyncGenerator — 비동기 스트림
  68. 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
  69. 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
  70. 70 folly::Expected — 결과 또는 오류
  71. 71 folly::Try — Future 결과 wrapper
  72. 72 folly::Try vs Expected 선택 기준
  73. 73 folly::Range — 일반 iterator pair
  74. 74 folly::Uri — URL 파서
  75. 75 folly Fingerprint64·128 — 분산 hash
  76. 76 folly SpookyHashV2 — fast non-crypto hash
  77. 77 folly::Init — main() 부트스트랩
  78. 78 folly::Indestructible — global lifetime 패턴
  79. 79 folly::MicroLock — 1-byte 락
  80. 80 folly::MicroSpinLock — 가장 좁은 spin lock
  81. 81 folly::format — legacy formatter 분석
  82. 82 folly::demangle — typeid 디망글링
  83. 83 folly::DynamicConverter — dynamic ↔ struct
  84. 84 folly::RecordIO — append-only 로그 파일 포맷
  85. 85 folly::io::Compression — zstd·lz4·snappy wrapper
  86. 86 folly::AsyncIO — io_uring·Linux AIO
  87. 87 folly::CancellationToken — 코루틴·Future 취소 전파
  88. 88 folly::observer — hot config의 atomic refresh
  89. 89 fbcode 패턴 모음 — folly 사용의 실전