Reputation: 13192
I'm looking for a data structure to store strings in. I require a function in the interface that takes a string as its only parameter and returns a reference/iterator/pointer/handle that can be used to retrieve the string for the rest of the lifetime of the data structure. Set membership, entry deletion etc. is not required.
I'm more concerned with memory usage than speed.
Upvotes: 4
Views: 21002
Reputation: 1
There are three ways to store strings:
Upvotes: 0
Reputation: 20142
One highly efficient data structure for storing strings is the Trie. This saves both memory and time by storing strings with common prefixes using the same memory.
You could use as the pointer returned the final marker of the string in the Trie, which uniquely identifies the string, and could be used to recreate the string by traversing the Trie upwards.
Upvotes: 16
Reputation: 29539
I think the keyword here is string interning, where you store only one copy of each distinct string. In Java, this is accomplished by String.intern()
:
String ref1 = "hello world".intern();
String ref2 = "HELLO WORLD".toLowerCase().intern();
assert ref1 == ref2;
Upvotes: 3
Reputation: 3323
I think the best bet here would be an ArrayList. The common implementations have some overhead from allocating extra space in the array for new elements, but if memory is such a requirement, you can allocate manually for each new element. It will be slower, but will only use the necessary memory for the string.
Upvotes: 0