Code Size Analysis#

pw_string: Efficient, easy, and safe string manipulation

Save code space by replacing snprintf#

The C standard library function snprintf is commonly used for string formatting. However, it isn’t optimized for embedded systems, and using it will bring in a lot of other standard library code that will inflate your binary size.

Size comparison: snprintf versus pw::StringBuilder#

The fixed code size cost of pw::StringBuilder is smaller than that of std::snprintf. Using only pw::StringBuilder’s << and append methods instead of snprintf leads to significant code size reductions.

However, there are cases when the incremental code size cost of pw::StringBuilder is similar to that of snprintf. For example, each argument to pw::StringBuilder’s << method expands to a function call, but one or two pw::StringBuilder appends may still have a smaller code size impact than a single snprintf call. Using pw::StringBuilder error handling will also impact code size in a way that is comparable to snprintf.

Label

Segment

Delta

Total StringBuilder cost when used alongside snprintf

FLASH

-4

[section .rodata]

-12

main

-8

vClearInterruptMaskFromISR

+4

__bi_84

NEW

+266

pw::string::IntToString<>()

NEW

+160

pw::string::internal::kPowersOf10

NEW

+92

pw::string_internal::InitializeStringBuffer<>()

NEW

+72

pw::string::DecimalDigitCount()

NEW

+38

pw::StringBuffer<>::StringBuffer()

NEW

+36

pw::StringBuilder::operator<< <>()

NEW

+28

pw::StringBuilder::operator<<()

NEW

+24

pw::StringBuilder::StringBuilder()

NEW

+14

pw::StringBuffer<>::operator<< <>()

NEW

+10

pw::ToString<>()

+720

StringBuilder cost when completely replacing snprintf

FLASH

-8

main

DEL

-40

__wrap_snprintf

+4

vClearInterruptMaskFromISR

NEW

+266

pw::string::IntToString<>()

NEW

+160

pw::string::internal::kPowersOf10

NEW

+92

pw::string_internal::InitializeStringBuffer<>()

NEW

+72

pw::string::DecimalDigitCount()

NEW

+38

pw::StringBuffer<>::StringBuffer()

NEW

+36

pw::StringBuilder::operator<< <>()

NEW

+28

pw::StringBuilder::operator<<()

NEW

+24

pw::StringBuilder::StringBuilder()

NEW

+14

pw::StringBuffer<>::operator<< <>()

NEW

+10

pw::ToString<>()

+696

Incremental cost relative to snprintf for 10 strings

FLASH

-40

[section .rodata]

-168

main

+14

pw::string::IntToString<>()

+36

pw::StringBuilder::operator<< <>()

+10

pw::ToString<>()

NEW

+28

pw::StringBuilder::operator<<()

-120

Size comparison: snprintf versus pw::string::Format#

The pw::string::Format functions have a small, fixed code size cost. However, relative to equivalent std::snprintf calls, there is no incremental code size cost to using pw::string::Format.

Note

The size report that is usually displayed here is temporarily unavailable while we migrate the pigweed.dev build system from GN to Bazel. See b/388905812 for updates.