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.
Smart Strings pool the internal objects they create while parsing and formatting. The global pool settings live in PoolSettings:
| Setting | Default | Description |
|---|---|---|
PoolSettings.IsPoolingEnabled |
true |
When true, pools track created and returned objects so they can be reused. When false, the pools still create instances but do not track them for reuse. |
PoolSettings.CheckReturnedObjectsExistInPool |
true in the Editor, false in players |
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. |
A single SmartFormatter instance, and the Parser 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.
Smart.Default is declared [ThreadStatic], so each thread that accesses it gets its own isolated SmartFormatter. As a result, Smart.Format and Smart.Default are safe to call from multiple threads, but configuration you apply to Smart.Default (such as extensions or settings) applies only to the thread that applied it.
Note: The internal object pools in this port run in single-thread mode. Do not share one SmartFormatter or Parser instance across threads. Use the thread-static Smart.Default, or give each thread its own instance.
Smart.Format(string, ...) parses the format string on every call. When you format the same template many times, parse it once and reuse the result. Call Parser.ParseFormat(string) to get a Format, then pass that Format to SmartFormatter.Format(Format, ...) repeatedly.
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 });
}
Format is pooled and implements IDisposable. The string overloads of Format return their parsed Format to the pool automatically, but a Format you obtain from ParseFormat is yours to manage: dispose it when you finish to return it to the pool. Do not use a Format after disposing it.
using var parsed = formatter.Parser.ParseFormat("Score: {Value}");
string result = formatter.Format(parsed, new Score { Value = 1 });