Does FString use the Small String Optimization?

I know that FString uses a TArray under the hood, and that in turn has an allocator instance as a member. I’m having trouble determining what allocator is being used and if it does optimize for small strings to avoid allocations.

Hi,

No, FString does not employ a small string optimisation. It ultimately uses the FHeapAllocator, because it just uses the default allocator parameter of TArray. FInlineAllocator is the allocator that would be used for SSO.

We have talked in the past about having a TString<AllocatorType> (and so FString would just be an alias of TString<FHeapAllocator>), but there hasn’t yet been any motivating factor to move this feature forward. We wouldn’t just change FString's default allocator, as there are many practical considerations involved there.

Steve

Thank you for the insight. I was curious since I have seen lots of code that will do something along the lines of MyString.Left(1) == TEXT("/") or MyString.Right(1) == TEXT("/") despite FString having StartsWith and EndsWith methods. I was thinking that maybe SSO was kicking in and might make comparing the result of Left and Right more efficient than StartsWith and EndsWith, but if those require a heap allocation, it seems as though StartsWith and EndsWith would be the better choice besides the fact that those methods also more clearly state intention and removes the possibility of accidentally passing in the wrong count in the call of Left and Right.

You are right - those cases would be better written using StartsWith() and EndsWith() - FString can do nothing to help optimise those cases. Well, it could use expression templates to re-form one as the other, but we’re not going down that route. :slight_smile:

Steve