3 ms·
I was under the impression that C strings were inherently very fast because of how incredibly cache-friendly they are. You should not ever have to count all the
by pitched 4y ago
I was under the impression that C strings were inherently very fast because of how incredibly cache-friendly they are. You should not ever have to count all the bytes (memoize that!) but if you do, this is the best format there is for it.
- Thiez 4y agoWhat makes you say that? Besides C strings (pointer to characters, null-terminated) we have Pascal strings (pointer to length, followed by the characters), and then there is the variant that I'm not sure what it's called, that consists of a pair of (pointer, length). The last variant is my favorite, an is much nicer to use: you can take substrings without making a copy, you never have to iterate a string to find out its length, and your strings can contain the NULL character (which happens to be a perfectly normal unicode character).
- WalterBright 4y agoI'm not sure what it's called In D we call them dynamic arrays. They could be called length-delineated strings.
- Thiez 4y agoIt seems that Wikipedia refers to them as "Strings as records"[1], which I suppose fits quite well. I suppose that C strings could be considered "the most" cache friendly since it has only 1 byte overhead instead of however many bytes would be required for the length (probably 4 or 8 bytes on most modern systems). That said, I would be extremely surprised for this difference of a few bytes per string to have a measurable performance improvement in anything but an unrealistic microbenchmark involving many tiny strings. 1: https://en.wikipedia.org/wiki/String_(computer_science)#Strings_as_records https://en.wikipedia.org/wiki/String_(computer_science)#Stri...
- WalterBright 4y ago0 terminated strings make sense for extremely tight memory cases, like 64Kb computers, and CPUs that don't cache memory. But they're a clear loser for 32 bit machines.
- mek6800d2 4y agoVAX/VMS called them "descriptors", which had IIRC 16 bits of flags, a 16-bit length, and a 32-bit pointer -- descriptors could be used for different object types, not just strings. The 64k length limit and 32-bit address were not a big issue back in 1982 when I first used them. I used (Wirth's standard) Pascal in our compiler class in college. String handling was actually pleasant in Fortran-77 on VMS, so I figured pure Pascal had the worst string handling of any language -- until I started programming in C. I finally made peace with C strings, but a couple of decades later, Forth said to me, "Here, hold my beer." I wrote some Forth-word equivalents of some of the C Library string functions to make my life a little easier! :)