Smart Strings performance
Reduce allocations and re-parsing when you format the same Smart String repeatedly, and understand the thread-safety constraints of a formatter.
Read time 2 minutesLast updated 5 days ago
Reduce allocations and re-parsing when you format the same Smart String repeatedly, and understand the thread-safety constraints of a formatter.
Smart Strings reuse internal objects through pools and let you cache a parsed format, so repeated formatting avoids most allocations and avoids re-parsing the format string. A formatter and its parser are built for single-threaded use, so plan how you share them across threads.
Object pooling
Smart Strings pool the internal objects they create while parsing and formatting. The global pool settings live in :
PoolSettingsSetting | Default | Description |
|---|---|---|
| | When |
| | A debug check that throws when an object is returned to a pool twice. It has a performance cost, so it is enabled only in the Editor. |
Thread safety
A single instance, and the it owns, are meant to be used from one thread at a time. Confine each instance to a single thread, or create a separate instance per thread.
SmartFormatterParserSmart.Default[ThreadStatic]SmartFormatterSmart.FormatSmart.DefaultSmart.DefaultReuse a parsed format
Smart.Format(string, ...)Parser.ParseFormat(string)FormatFormatSmartFormatter.Format(Format, ...)var formatter = Smart.Default; // Parse once. Format parsed = formatter.Parser.ParseFormat("Score: {Value}"); // Format many times without re-parsing. for (var i = 0; i < 10; i++) { string result = formatter.Format(parsed, new Score { Value = i }); }
FormatIDisposableFormatFormatFormatParseFormatFormatusing var parsed = formatter.Parser.ParseFormat("Score: {Value}"); string result = formatter.Format(parsed, new Score { Value = 1 });