Module

stringbuilder

StringBuilder for O(n) string accumulation.

Adopts kida's proven StringBuilder pattern for efficient HTML output. Appends to a list, joins once at the end: O(n) total vs O(n²) for repeated string concatenation.

Thread Safety:

StringBuilder instances are local to each render() call. No shared mutable state.

Performance:

For a 1000-line document with 500 rendered fragments:

  • String concatenation: ~125,000 character copies
  • StringBuilder: ~25,000 character copies (5x faster)

Classes

StringBuilder 8
Efficient string accumulator. Appends to a list, joins once at the end. O(n) total vs O(n²) for re…

Efficient string accumulator.

Appends to a list, joins once at the end. O(n) total vs O(n²) for repeated string concatenation.

Usage:

    >>> sb = StringBuilder()
    >>> sb.append("<h1>")
    >>> sb.append("Hello")
    >>> sb.append("</h1>")
    >>> sb.build()
    '<h1>Hello</h1>'

Thread Safety:

Instance is local to each render() call.
No shared mutable state.

Methods

append 1 StringBuilder
Append a string to the builder.
def append(self, s: str) -> StringBuilder
Parameters
Name Type Description
s

String to append (empty strings are skipped)

Returns
StringBuilder self for method chaining
append_line 1 StringBuilder
Append a string followed by newline.
def append_line(self, s: str = '') -> StringBuilder
Parameters
Name Type Description
s

String to append (empty = just newline)

Default:''
Returns
StringBuilder self for method chaining
extend 1 StringBuilder
Append multiple strings at once.
def extend(self, strings: list[str]) -> StringBuilder
Parameters
Name Type Description
strings

List of strings to append

Returns
StringBuilder self for method chaining
build 0 str
Join all parts into final string.
def build(self) -> str
Returns
str Concatenated string of all appended parts
clear 0 StringBuilder
Clear all accumulated parts.
def clear(self) -> StringBuilder
Returns
StringBuilder self for method chaining
Internal Methods 3
__init__ 0
Initialize empty StringBuilder.
def __init__(self) -> None
__len__ 0 int
Return number of parts (not total length).
def __len__(self) -> int
Returns
int
__bool__ 0 bool
Return True if any parts have been appended.
def __bool__(self) -> bool
Returns
bool