r/ProgrammingLanguages • u/funcieq • May 23 '26
Discussion How to implement String?
Currently, String in my language is just value and length because it's a temporary solution, And as the language has developed, I am now able to rewrite a lot just for it, so I want to make a decent String in my language. So my question is, which String concept annoys you the least?
47
Upvotes
54
u/faiface May 23 '26
It highly depends on how your language works, but the approach I’m fond of the most is the combination of:
- An immutable, ref counted / garbage collected, string value (internally then byte array + length)
- A string builder
27
u/evincarofautumn May 23 '26
Raku, Swift, and Rust are good examples of different approaches to modern string design
General tips:
16
u/s0litar1us May 23 '26
The simple solution works fine for most things
If you want to deal with appending, etc. then something closer to a dynamic array would be useful
The approach I prefer the most is to have just a length for most strings, and have a separate thing for building larger strings.
8
u/Usual_Office_1740 May 23 '26
Without knowing more about your language it is hard to give useful input. I can't comment on what annoys me about strings the most because they seem to work roughly the same way in popular languages. They're packed structs of some kind that house a pointer to heap memory and a length, or a pointer and a sentinal marker.
I like Rusts design approach. Instead of implementing a custom string type consider implementing custom fixed and dynamic length arrays and then use those to build a string?
8
u/Sad-Grocery-1570 May 24 '26
This question is best approached from two angles: What is the logical model of a String? That determines the interface and safety guarantees you expose to users. What is the underlying implementation? That determines how you trade off complexity and performance, and how you handle system-level and cross-language interactions.
On the logical model, here are a few possible approaches:
On the underlying implementation, here are a few possible approaches:
The logical model and the implementation can basically be mixed and matched freely, though some combinations feel more natural than others. Existing designs aren't necessarily the best; what matters most is fitting your use case.
5
u/gabrielesilinic May 23 '26
My opinion is that you should make a string an immutable array of characters. And pick your encoding depending on the environment. Most popular choices are both utf8 and utf16.
Then you might make your stringbuilder tooling separately.
And yes. Please make the length an explicit number. C's /0 sentinel caused an incredible amount of trouble with string copy and such
5
u/eightrx May 23 '26
I like zig's unambiguous
[]const u8andArrayList(u8)for constant and dynamic strings16
u/mamcx May 23 '26
Try to not innovate! You will need to interop with the world!
uft-8for default. There is not a good reason to not pick it as your default. Whatever excuse exist that could be considered good, is for a secondary kind of string.Stringis immutable you should separate manipulate/inspect their bytes vs chars, at minimumI think this is the MVP.
4
u/runningOverA May 23 '26
an attribute indicating if the string is a snapshot into another string ie. sub string.
95% of cases you will be working with snapshots into a larger string.
like loading a configuration file or a json.
snapshots make memory management easier and increases performance.
3
u/Rememba_me May 23 '26
Check out german style strings
4
u/szarawyszczur May 23 '26
Char*
7
u/baehyunsol Sodigy May 24 '26
My language uses char-array instead of byte-array, so it's a utf-32. I chose this because
Even though many of you're not gonna agree, I don't think utf-32 have significant performance disadvantage. Memory is cheap, unless you're training an AI model. A million characters string consumes 1~3MB (depending on your nationality), which is very small for today's RAM. There are rare cases you want to deal with strings bigger than that. If you have to handle a billion characters string, it's likely that your CPU is bottleneck, not your RAM.
6
u/brucejbell sard May 24 '26 edited May 24 '26
I am tired of weak string support in C/C++, I want industrial strength strings in my systems programming language:
All this should be fire-and-forget: just use the core string API and your string operations will be fast and memory-efficient, Javascript style.
(If your environment is so constrained that you can't afford any kind of heap allocation, there should be affordances to limit string operations accordingly)
4
u/tobega May 24 '26
One thing that really annoys me is strings that are considered to be an array of characters.
The only legitimate uses for strings are to hold sequences of human language, and, I will concede, also opaque identifiers or labels. So they are things that are whole in themselves, not a list of things (except maybe glyphs, but I'm not sure that all languages decompose cleanly to glyphs).
Ask any human, text is not an array of characters, nobody reads it like that. So array of characters is a huge concession to the primitive computing machine, we don't need to do that any longer.
Whatever you do, please go the extra mile and make sure it works for all languages! The focus on American English in particular has been a real difficulty with computers and computers tooling well into this century.
FWIW I have a very small paragraph about text in my post https://tobega.blogspot.com/2024/01/usability-in-programming-language.html
2
u/kreiger May 24 '26
With modern Unicode character encodings, a code point is represented by a variable number of bytes, unless you use UTF-32.
You want to make it easy for the programmer to iterate over the code points of a string.
It follows that the bytes that make up the encoding of a string shouldn't be indexable, because it encourages programmers to make the mistake of treating a single byte as a code point.
2
u/Key_River7180 Nain. May 26 '26
Use NUL-terminated strings, they are universal.
2
u/EggplantExtra4946 May 26 '26 edited May 26 '26
What annoys me the most it that the character encoding is not part of the string type.
If it were part of the type, as a type parameter, you wouldn't be able to generate mojibake by mistake in your language, and you would interpret input text correctly, assuming the input is not mixing up several encodings which happens on the web, and assuming that the only way you can construct the string type of a given character encoding is through a character encoding validation function.
1
u/cisterlang May 23 '26
To all advocating immut strings, how about altering a single char in a huge string ? I have trouble with the idea of allocating anew.
1
u/carangil May 24 '26
I went with immutable, reference counted UTF-8. The string header has a length, but the string is also kept NULL terminated for easy interop with C.
If the user wants to modify/build strings, they can convert to a mutable Byte array, which is a copy. And you can copy Byte arrays into a new String.
It was also very easy to add the optimization that if your String or Byte aray has only 1 reference, 'converting' just changes type without a copy.
1
u/Pretty_Jellyfish4921 May 24 '26
As others recommended, I also think Rust approach works well, String (dynamic size) is a wrapper around a vector, so if you already have a vector implementation, then you have already a String. As for the immutable strings, you could also apply some optimizations if it is short enough to fit into a u32 or u64 (depending on your pointer size) and lastly there's a slice or string that is a reference that points to a string with a start and a length (maybe you could have just the pointer to point to the start and a length (that most of the time you can squeeze into a ptr size, by using one or two bytes from the u32/u64 for the length), so you don't need to copy the string all over the place.
1
u/zweiler1 🔥 Flint May 24 '26 edited May 30 '26
In my language strings are just defined as
so it's one structure allocated on the heap with a variable-member pattern, and the value ends with a null-terminator too to make C interop easier (just pass the equivalent of
s.valueto the C function, it will be a null-terminatedchar*this way) and you don't have any indirections either.I have kept strings as simple as possible, so no utf-8 support or similar things yet. But this pattern is one i think works best for me until now, it's easy to work with and fast enough.
1
u/zyxzevn UnSeen May 24 '26
It depends on the rest of your language, and on the projects.
From my experience with Delphi (huge office-style project with lots of texts), I learned that ref-counting is usually fast enough. And easy to use.
{ length, capacity, ref-count, data_ptr }
The data ptr is a nul-terminated string, and can be directly used for C-strings.
For specific projects there is always a better solution, but I think that the easiest one is good enough in practice.
If projects have a well defined string flow (like compilers), the strings can be saved in an arena-allocator (temporary storage) for speed. Also many other programs do not even bother to free the string memory used (with today's RAM prices!).
1
u/BrangdonJ May 24 '26
I made my own C++ string class back before
std::stringwas a thing, and kept using it. My main regret was providing an implicit conversion to(const char *), which proved all but impossible to remove later. Presumably that wouldn't be an issue for a new language.My strings were shared but mutable, with copy-on-write. The representation was a counted pointer to a descriptor that had length, capacity and the character bytes. Zero-length strings could use a special static descriptor, so they didn't need a memory allocation. I liked that
sizeof(String) == sizeof(char *).I didn't expose non-const iterators like
std::stringdoes. You could modify using functions likes.set(i, 'c'), that checked the ref-count to see if the string was shared, and reallocated if necessary. If you needed more efficiency I used aGetBufferSetLength()approach, that returned a raw pointer. In another language I'd probably use a non-shared StringBuilder class.I found being able to copy strings cheaply was important. It bothers me that copying std::string might mean a heap allocation, because they get copied a lot I also found that being able to modify them in-place was convenient even if it was relatively inefficient (with the copy-on-write). Sometimes the efficiency wasn't important.
Most strings use UTF-8, but I had UTF-16 and UTF-32 available for when you need them for compatibility. Indexing was by byte in the UTF-8 case. I had functions like
nextCodePoint()for when you need to process as Unicode code points. I found code rarely cared about things like whether an accented character was one code point or two. I used a third party library for things like uncased comparisons, that handled things like whether "FI" is equal to the fi ligature. I avoided assuming that, eg, uppercasing a string wouldn't change its length. In general you shouldn't be uppercasing individual characters.I considered other representations over the years but it never seemed worth it. For example, using three pointers: one to the descriptor, one to the start of the bytes, and one to the end. That would allow cheap sub-strings, but made each string three times the size.
1
u/Brave-Ad-8201 May 24 '26
Eu particulamente tenho preferência por string imutável. Acho que isso deixa o comportamento mais previsível: se uma função recebe uma string, eu não preciso ficar pensando se ela pode alterar o conteúdo original.
Uma ideia que talvez ajude é separar bem as operações: internamente a string pode ser UTF-8 e guardar o tamanho em bytes, mas a linguagem deveria deixar claro quando uma função está lidando com bytes e quando está lidando com caracteres. Isso evitaria muita confusão.
1
u/sazasoo May 25 '26
I can't say for sure which concept annoys me the least, but the one that annoys me the most is defintelly char*. But an idea to adapt the string concept you are already using (pointer, length) could be to expand it to include capacity, that would allow the string to act as a dynamic buffer. length is how many characters you currently have, and capacity would be the actual memory footprint allocated, so if a user appends text, just write into the pre-allocated extra space and increment the length without triggering an expensive malloc/free cycle, only reallocating when length equals capacity.
1
u/ChiveSalad May 25 '26 edited May 25 '26
Wrong answers only
(for entities that are functions with closures, I lost discipline and so the size of FunctionBits got so big that the string case in the union got big enough to be kinda usable- when it's not long enough, linked lists of 32 element segments is fine, the language is terrible anyways)
1
u/First-Review5604 May 26 '26
The best approach is usually the most "predictable": immutable strings with UTF-8 support by default.
The least annoying concept (and the modern standard) is strings as immutable byte arrays with a header that stores the size and, optionally, a pre-calculated hash for quick comparisons.
1
u/LordKisuke May 30 '26
Honestly, your current setup (pointer + length) is already way better than C's null-terminated mess. I'd just stick to that and make sure you go with UTF-8 everywhere. It's way more memory efficient for standard text and backwards compatible with ASCII. UTF-16 is just pain, dealing with surrogate pairs is a nightmare you really don't need