3 ms·
Is there any reason not to use snprintf for almost every application of string manipulation (aside from strduping)?
by kdelok 8y ago
Is there any reason not to use snprintf for almost every application of string manipulation (aside from strduping)?
- hxchen 8y agoReason: performance. If you just do string manipulation, memncpy is faster. If you need to convert data type, like int to string, then use snprintf.
- nneonneo 8y agoYes, it seems I lied when I said sprintf is surprisingly fast. For most practical purposes it's fine, but if you need to do string manipulation in a hurry, strcpy/strlcpy are going to be faster. See https://gist.github.com/nneonneo/f9dc5c1d1d342d25eae47d56dbad040e https://gist.github.com/nneonneo/f9dc5c1d1d342d25eae47d56dba... for a test harness. On my Mac, with a 16-byte string, 10 million loops: memcpy: 77406 us strlcpy: 101956 us strncpy: 177247 us sprintf: 730819 us snprintf: 699844 us memcpy smokes sprintf - around 10x faster. The vast majority of sprintf's time is spent in setup; for large strings, the gap closes substantially.