Skip to content
Tcl Source Code An experiment with small string optimization
Login

An experiment with small string optimization

This page describes my attempt to implement small string optimization for Tcl. I most likely will not pursue this further for reasons stated below. Just recording for posterity in case someone has similar thoughts in the future where my experience might have some use. The implementation is in the apn-ss-wip branch.

The basic idea is simple enough. Instead of allocating separate storage for storing the short strings (14 chars or less on 64-bit platforms), they can be stored in the internalRep field within the Tcl_Obj itself. Saving the extra allocation speeds up operations like string index and (small) string range by more than 20%. That was significant enough to explore it further.

At the end, I concluded it was not worth pursuing for two reasons - limited applicability and significant test effort.

The limited applicability comes from multiple factors:

The final straw was however the issue with testing. A very large number of tests use shorts string like "abc". Addition of short string objects would mean all these tests need to be duplicated to exercise the long string paths. Just too much work.

Quite possibly the issues above would have been obvious to others up front :-) I did anticipate them to some extent but was hoping for wider applicability of the performance benefits.


On 2026-01-08 06:23:53 UTC chw added:

What about a slightly different but in consequence equivalent approach?

Make the allocation of a Tcl_Obj somewhat larger to fit a cache line (64 bytes in most cases, instead of 48 (64 bit arch) or 24 (32 bit arch) and use the additional space for small strings.

Ideally the allocation is constrained to align proper on 64 byte boundaries (or whatever the cache line size is).

The only thing to consider (and to test) then is when to use that additional space, and when (not) to free the (not) allocated string buffer. Which might keep the required code changes rather minimal.

32 bit architectures would benefit more, since small strings can use 40 extra bytes in contrast to 16 for 64 architectures.