StringInterning class

A string interning system that reduces memory usage by storing only one copy of identical strings.

String interning is particularly beneficial for metadata tags where many files may share common values like genre names, artist names, or album names. Instead of storing duplicate strings in memory, the interning system maintains a single canonical copy that can be referenced by multiple tags.

Benefits

  • Memory Reduction: Eliminates duplicate string storage
  • Cache Efficiency: Better CPU cache utilization with fewer unique strings
  • Comparison Speed: Interned strings can use reference equality
  • Collection Performance: Reduced memory pressure improves GC performance

Usage Examples

final interning = StringInterning();

// Common genre names will be interned
final rock1 = interning.intern('Rock');
final rock2 = interning.intern('Rock');
assert(identical(rock1, rock2)); // Same object reference

// Artist names across multiple files
final artist1 = interning.intern('The Beatles');
final artist2 = interning.intern('The Beatles');
assert(identical(artist1, artist2)); // Memory saved

// Check memory usage
print('Interned strings: ${interning.size}');
print('Memory saved: ${interning.estimatedMemorySaved} bytes');

// Clear when done processing a batch
interning.clear();

Thread Safety

This implementation is not thread-safe. Use separate instances per thread or add external synchronization if needed.

Memory Management

The interning system uses weak references where possible to allow garbage collection of unused strings. Call clear periodically to release memory when processing large batches of files.

Constructors

StringInterning.new()

Properties

estimatedMemorySaved int
Estimates the memory saved by interning in bytes.
no setter
hashCode int
The hash code for this object.
no setterinherited
hitRatio double
Returns the cache hit ratio as a percentage (0.0 to 1.0).
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
size int
Returns the number of unique strings currently interned.
no setter
statistics Map<String, dynamic>
Returns statistics about the interning system performance.
no setter

Methods

clear() → void
Clears all interned strings and resets statistics.
intern(String value) String
Interns a string, returning the canonical instance.
internIfBeneficial(String value) String
Interns a string only if it's likely to provide memory benefits.
isInterned(String value) bool
Returns whether a string is currently interned.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited