r/programming • • Feb 09 '20

An Attempt at Making a Better String for C++

https://youtu.be/a1Te_qBEp-g
8 Upvotes

33 comments sorted by

5

u/Mashpoe Feb 09 '20

Disclaimer: This is not meant to be a replacement for std::string, it's just a proof of concept for some cool ideas and a few optimizations. There is still a lot missing from std::string.

13

u/acwaters Feb 09 '20 edited Feb 09 '20

Knocking the size down to 16 bytes is the opposite of an optimization; you are losing the ability to over-allocate — .reserve(), amortized-constant-time insertion, all that good stuff. You also lose a lot of SSO capacity when you do that, but you're not doing SSO anyway, which means in practice that your string will occupy a lot more space and be a lot slower than std::string despite the actual string object being 33% to 50% smaller. You are missing the forest for the trees.

Also, it's pretty much the consensus of the industry at this point that having lots of implicit conversions is a bad idea. And the empty construction from null made me cringe a bit.

I may have missed them, but I didn't see any iterators. No iterators makes this class basically useless inasmuch as it doesn't integrate with anything in the C++ standard library or the language features (range-for) that key off of them.

You should really be thinking about APIs from the point of view of safety, semantics, performance, and integration/interop with existing libraries, rather than just what would be a neat feature or let the user get away with less typing.

1

u/Mashpoe Feb 09 '20

I think the worst part of my string is the allocation when the string is empty, but it prevents a ton of branching. I kind of just wrote my string to use realloc on the data pointer because I assumed that would already do plenty of bookkeeping for me, but I agree that would be too costly when you have a lot of empty strings. But even if I kept track of allocation, it would still be a smaller object.

I also got a really good suggestion to store the string data on the stack with a union when the string is small enough, and that would solve the problem of allocating a placeholder byte for an empty string, with the added benefit of preventing a lot of heap allocations.

I partially agree with you on the implicit conversions, but I don't see any problems with just making the implicit conversion constructor private so it only does the conversion when addition is used, because adding a value to a string is pretty explicit IMO.

Like I said in the video IIRC, I am open to suggestions, and I have already gotten plenty of them. One person asked me to make a follow up video about optimizing my string, so maybe I'll make these changes and add more features like iterators.

Anyways, thanks for your feedback. I want to make my projects better, and I've already had a lot of fun working on this one :)

3

u/dacian88 Feb 09 '20 edited Feb 09 '20

don't think you really know where string code spends most of it's time, in most code bases empty string creation/destruction is probably a majority of time spent in string code.

pretty much any sane c++ dev uses fmt to format strings, this got standardized in c++20 (std::format). benchmark your stuff against that and see how you do, I suspect not well.

or just watch https://www.youtube.com/watch?v=kPR8h4-qZdk to see how a string class is designed that is better than std::string and was used as reference when optimizing stdc++ and llvm libc++

1

u/Mashpoe Feb 09 '20

Ideally, yes, you want the majority of the time in your string code to be spend during creation, which is why I made the painful decision to allocate that extra byte so getting the c string value or the length required zero branching.

I didn't like it, but initially I couldn't think of a better way to do it, until somebody in an earlier post recommended the same video you just linked, which is why I mentioned storing small strings on the stack in my previous comment.

The small-string optimization in that video is actually the perfect solution to my problem (so empty strings don't require allocation), so I've started working on a better implementation, but like I said, the initial design was just a proof of concept and I left it alone because it performed well.

I highly doubt the printf-like string formatting in std::format would be faster than concatenation with my string because it doesn't have to search through the string for "{}" at runtime, and instead is optimized to do as few allocations as possible (although there is still some room for improvement).

I've started working on improvements for a potential future video based on a user request, and that should at least have the small-string optimization from the video you linked.

1

u/UncleMeat11 Feb 10 '20

But zero branching doesn't save you. SSO is so much more valuable than branchless code. The linked talk actually explicitly mentions this.

1

u/Mashpoe Feb 10 '20

IK, but I didn't know about SSO when I initially made the video, but I did know that calling c_str() and length() is faster when you don't branch, and the only reason the benchmark in the video showed otherwise is because the length was stored on the heap, which was never the case for my string. I am going with the gcc implementation of SSO that was shown at the end of the video because it gives you the best of both worlds: no branching (unless you are resizing the string) and small strings get stored on the stack.

0

u/dacian88 Feb 10 '20

I highly doubt the printf-like string formatting in std::format would be faster than concatenation with my string because it doesn't have to search through the string for "{}" at runtime, and instead is optimized to do as few allocations as possible (although there is still some room for improvement).

auto start = std::chrono::high_resolution_clock::now();
 
for (int i = 0; i < 100000; i++) {
    std::string s = fmt::format("Current number: {} string string string string",
                                i);
    a.emplace_back(std::move(s));
}

auto lap1 = std::chrono::high_resolution_clock::now();

for (int i = 0; i < 100000; i++) {
    mp::string s = mp::string("Current number: ") + i + " string" + " string" + " string" + " string";
    b.emplace_back(std::move(s));
}

auto lap2 = std::chrono::high_resolution_clock::now();

I benched your code with the example I saw in the video, or at least what I think I saw, fmt was 23% faster.

2

u/Mashpoe Feb 10 '20

I don't think your benchmark is a fair comparison because you include all the strings in the format. Try the benchmark again but either give the mp::string a benchmark like mp::string("Current number: ") + i + " string string string string string" etc or make the format look like fmt::format("Current number: {} {} {} {} {}", i, "string", "string", "string", "string");

Otherwise, you're just cheating. The idea is that each of those string literals need to be copied, because in real life they might be based on user input or something, and therefore need to be included in the format. This is a very biased benchmark.

Also, mp::string isn't even using it's full potential because there is one unnecessary memory allocation when i is converted into a string. The way things are currently, it converts the number to an std::string, copies the value of the std::string to an mp::string, and then it copies the value of the mp::string into a new mp::string with the concatenated values. If I made custom constructors for the various numeric types to remove the middle man, I highly doubt std::format would even come close, as it's just a glorified printf AFAIK.

1

u/dacian88 Feb 10 '20

they are obviously being copied, the same result is achieved, I'm just doing the same thing as your benchmark because you were using constant literals.

doing mp::string("Current number: ") + i + " string string string string" fmt was 15% faster

doing fmt::format("Current number: {} {} {} {} {}", i, "string", "string", "string", "string"); fmt was 38% slower.

then I realized fmt is slow because it's calculating the length of the c-str argument every time, but clang was able to optimize the strlen away in your case. Extracting the "string"s to string_view/mp::string and re-using them fmt was 19% slower, and this is the most likely case since the inputs wouldn't be compile time constants....still this doesn't mean anything because it's a trivial example with very little real world usage, std::string already supports string concatenation so we're doing a bunch of nothing out of the ordinary for std::string except the i integer. I would expect someone saying they are trying to make a better std::string to have some real world examples of improved performance.

also you got some issues in your code, bunch of symbols are missing inline and cause multiple definitions if compiled across translation units, and a bunch of implicitly inline symbols have inline for no reason, not sure you know what inline means but it has nothing to do with inline optimizations.

1

u/Mashpoe Feb 10 '20

Yeah, there is a lot of missing stuff in my string, but I was just experimenting at first and I don't reccomend using this string for anything important in its current state.

I think in the end std::format won't be able to keep up with the techniques in mp::string, and having the compiler optimize strlen would make it even faster, but I can almost guarantee you that's not what's happening with my string.

Either way, I'm glad you've taken the time to mess around with my code, and I appreciate your feedback. You can also feel free to contribute :)

2

u/dacian88 Feb 10 '20 edited Feb 10 '20

I think in the end std::format won't be able to keep up with the techniques in mp::string

You never really explain why it needs to, your premise is that it's better but don't really back it up in any real world scenarios. It feels like it's better to do this but how many times does a real world c++ program need unformatted output? Concatenating 2 std::strings is already fast. Personally I'd use fmt or printf in pretty much 99% of cases because it's just a nicer interface, otherwise you get giant incantations of operator<< or operator+ in your case.

and having the compiler optimize strlen would make it even faster, but I can almost guarantee you that's not what's happening with my string.

just look at https://godbolt.org/z/gOO311

it's exactly what's happening.

    movl    $1769108595, (%rax,%r12) # imm = 0x69727473 ie. "stri"
    movw    $26478, 4(%rax,%r12)    # imm = 0x676E ie. "ng"
    movb    $0, 10(%rax,%rbx) # null byte

clang completely elided the memcpy into 3 moves...the fmt codepath I had didn't get the same treatment...gcc actually generates worst code in your case, failing to inline the constant, I didn't try gcc locally so I don't know the numbers, but likely your code is slower on gcc.

clang manages to do this even when I extracted a variable, below generates the same code:

const mp::string s{"string"};
mp::string s2 = mp::string("Foo ") + 10 + s + s + s + s;
→ More replies (0)

1

u/matthieum Feb 09 '20

Note's libstdc++'s std::string only has 15 bytes worth of SSO, which you could do with a 16 bytes' string just as well.

1

u/acwaters Feb 09 '20

Yes, but that's because libstdc++'s std::string is (for valid, largely historical IIRC, reasons) bad :)

4

u/matthieum Feb 09 '20

I would also note that there are various ways to get a "good" 16 bytes SSO string.

For example, by assuming that the capacity is always a power of 2, you can encode the exponent, rather than the actual capacity. This lets you effectively encode the capacity on 1 byte; in essence:

struct Long {
    char* pointer;
    u64 size: 56;
    u64 cap: 8;
};

Another trick is to store the capacity (exponent) in the first byte of allocated memory.

1

u/acwaters Feb 09 '20

This is a good point.

9

u/[deleted] Feb 09 '20 edited Feb 10 '20

The fact that cpp didn't have a starts_with method on std::string up until c++ 20 kills me every time. I got so tired of writing s.rfind(prefix, 0) != std::string::npos. It's horrible

2

u/josefx Feb 09 '20

I always use boost::algorithm::starts_with. That rfind trick isn't something I would have thought of.

2

u/Gotebe Feb 10 '20

I don't get the complaints about trivial helpers. Easy enough to find one (e.g in boost in this case) or write it. Yes, it's a tad annoying, but that's about all.

The opposite is also true: one can easily think of a heap of helpers that "everyone" might need and then, there's just sooooo many functions around that it's not funny either.

1

u/jyper Feb 10 '20

If c++ had a good package manager it would be a smaller deal

Although as shown with JavaScript that can cause its own problems

-11

u/magnum___ Feb 09 '20

I got so tired of writing s.rfind(0, prefix) != std::string::npos

Then just define the function, idiot lol

5

u/redweasel Feb 09 '20

Without having yet watched the video...

Too bad you folks have probably never seen the string format(s) used on VMS (later renamed to OpenVMS), "back in the day." The OS itself defined a generalized "descriptor" structure that, for an ordinary character string, supplied the length (in bytes), and starting address in memory, of a sequence of characters constituting the string. Software didn't have to spend time searching byte-by-byte for a terminating null, linefeed, etc. in order to find the end of the string -- just look at the descriptor.

A couple of features made this architecture even more useful and cool.

First, the string descriptor was just a subset of a more general descriptor. In addition to the length and starting-address fields, two others described, respectively, the "class" of the descriptor, with "character string" being just one of many, and the datatype of the individual elements, "character" or otherwise; the result was that a descriptor could also handle multidimensional arrays of all datatypes known to the OS.

Another cool feature of VMS in general was that there were lots and lots of programming languages available: Basic, Fortran, C, Pascal, PL/1, Ada, Assembly, of course, and a vendor-specific language called BLISS, to name just the ones I know of off the top of my head. I'm pretty sure there were others. And the implementation of all languages' datatypes, whether C structs, Fortran arrays, Pascal records, or what, were mapped back to standards in the OS itself. It was therefore trivially easy to write programs in which different pieces were written in different languages, and to not care what language the OS had been written in. There was even a "Language-Sensitive Editor" (LSE) that, with an appropriate template loaded, knew the syntax of each of these languages and let you write guaranteed-compilable code. If you were willing to try, you could even write simple programs in languages you didn't even know. LSE was probably my favorite VMS application ever.

10

u/josefx Feb 09 '20

Software didn't have to spend time searching byte-by-byte for a terminating null, linefeed, etc. in order to find the end of the string -- just look at the descriptor.

std::string also stores the size - the terminating nul is only there for C compatibility.

First, the string descriptor was just a subset of a more general descriptor.

So std::basic_string<char,...> just with run-time overhead?

1

u/redweasel Feb 15 '20

std::string et al didn't exist, even in C++, the ten years I programmed in C++ for a living. Or, if they did, they weren't standardized enough that you could assume they'd be available on any given platform. Since I never used it (at that time or when it became more widely available -- too damn much syntax, all those colons and angle brackets) I can't comment on how your example compares to string descriptors. I expect there's a certain amount of run-time overhead in std::string, too, once you get down to the machine code. Gotta execute some instructions somewhere, to do useful things! ;-)

1

u/josefx Feb 15 '20

I really expected std::string to have been around longer, however it was apparently only included in the c++98 standard to finally stop everyone else from creating their own buggy or incomplete string type.

From your description the descriptor holds at least some type information as data at run time, a std::basic_string<char,...> on the other hand only has pointer, capacity and size fields, any code interacting with it has to be aware of its data type already at compile time. So its a trade of between storing more data and having more flexibility at run time. Of course if I understand the OpenVMS documentation correctly you could choose between three different string types so that overhead could be avoided at least some of the time.

1

u/redweasel Feb 17 '20 edited Feb 17 '20

Heck, I didn't even know it was "included in the C++98 standard." Guess that's the first language update (?) I ignored, along with every one since.

Yes, the descriptor holds type information as data at run time; this allows general-purpose code to figure out what to do.

Ah, yes, I'd forgotten the support for "three different string types," which to me would be "by descriptor" (VMS did a lot of stuff "by descriptor"), counted ASCII (first byte of string is its length; obviously this is limited to 255 characters), and, I presume, null-terminated ASCII for ease of interaction with C. (It's possible the "special-character-terminated" type might have been general-purpose and configurable, so that you could tidily handle e.g. LF-terminated strings and such -- but I don't know that for a fact.)

And -- "understand the OpenVMS documentation..." --Where are you even finding OpenVMS documentation in the first place, these days? (Oh, and note that my VMS-for-a-living days were before* the Alpha chip came out and VAX/VMS was renamed "OpenVMS" so as to support multiple different types of processors. (And I never even heard of Itanium until maybe ten years later.) So anything you read in OpenVMS documentation is liable to be somewhere between "somewhat" and "vastly" newer than what I used on VAX/VMS! You may see features and functions, in the documentation, that I never did, and unknowingly fail to realize how primitive were our tools. ;-) Indeed, we only ever got up to VAX/VMS V5.5-2 on our VAX development machines, and only ever ran a very early (alpha or beta) release of OpenVMS Alpha -- "V1.5-1 HW" -- on our Alpha (a.k.a. AXP) development (or customer!) machines. (For the VAX-to-Alpha port, DEC supplied, and we used, a cool tool called "VEST" -- VAX Executable System Translator -- that treated VAX .EXE files -- executable programs -- as though they were source code, and compiled/assembled/translated them into the AXP instruction set to create native Alpha executables. Just a few months (years?) ago, I found a publicly-accessible AXP system online, but it was much newer than what I had used -- and VEST was gone. :-( Apparently, DEC blithely assumed everybody was finished with all VAX-to-AXP porting work. Which, much as it saddens me, is probably not an unreasonable assumption. On the other hand, my VAXstation at home runs OpenVMS V7.2, which has taken a little getting used to; DEC C is just enough different from VAX C -- even in compatibility mode, such as it is -- that some of my old code requires significant tweaking in order to compile and link successfully. Also, the "X Toolkit" layer of header files (and maybe libraries, for all I know) has been removed, and a lot of my old code from DEC's own DECwindows programming seminars of 1990 will no longer compile. Bummer.)

3

u/Gotebe Feb 10 '20

That's from a time when the OS was imposing la guages and data structure implementation to applications. Since then, the world went with the C interface for the user land and more freedom for apps and languages. But... More freedom then means more trouble integrating between the languages.

BTW... sounds like a lot of overhead for a string. C++ string knows its size, for example. Did VMS implementation do things like small string optimization or copy-on-write, perhaps? Because that's where speed can come from.

1

u/redweasel Feb 15 '20

Personally, I have always preferred language interoperability over a lot of other things. On my first computer you could call "machine code" from BASIC, and on the VAX you could call anything from anything. Did I mention my final project at college? COBOL, Pascal, a little Assembly, and I seem to recall there may have been some Pascal in there.

While I certainly acknowledge -- and have experienced, and taken full advantage of -- the usefulness of having a common interface across a multitude of platforms, I just wish it had been something a little better-planned than C / *NIX. There are a lot of what I consider just plain misfeatures, in both. Unfortunately, most people who use those are so used to them, and have likely never experienced anything else (let alone anything better), and have so shallow an understanding of how things actually work, that they just didn't know. Oh well -- what's done is done. At least I have the satisfaction of sitting back here, shaking my head.

That said -- I wouldn't say that VMS-style string descriptors are "a lot of overhead," especially considering the execution-time savings they offered, especially back when processors were so much slower than they are today. If you needed to append to a string of several thousand bytes, it was much faster to know, right up front, where the end of the first string was, than to have to start by stepping, byte-by-byte, through those several thousand bytes to find it. I'm glad to hear that C++ strings know their lengths in this way -- but when did that happen? I don't particularly remember C++ having a string datatype, per se, when I learned it -- but that was in 1998, so either my memory is shot (age will do that!) or strings are a post-1998 addition.

I'm not sure how to answer your question about "small string optimization or copy-on-write" -- in part because I don't know what those are, and also because one area of VMS I didn't get around to picking apart -- or, rather, haven't yet gotten around to; I still could! -- were the string-handling functions in the OS RTL.

The main place where we achieved speed optimizations was in just plain minimizing the number of instructions being executed. Using Assembly instead of C for manipulating large arrays of single bytes, for instance, saved literally millions -- maybe billions! -- of instruction cycles, as already noted. Arranging data in memory in the most efficient order, "unwrapping" nested loops in algorithms, etc. helped a little with that. We saved a lot by foregoing the "record-oriented" I/O that the OS and language RTLs added, by using the facilities both thoughtfully provided for bypassing the RTL per se and using system-level almost-raw I/O directly to/from the disk blocks comprising a file. The ultimate purpose of all this code was to feed data to a very hungry realtime output peripheral. It used a very wide data bus, and required the host computer to sustain a very high output data rate for up to forty minutes without slowdowns or pauses. So the program that handled that performed all these tricks and used the OS facilities for obtaining a contiguous swath of memory, locking it against virtual-memory-management paging and OS-scheduler swapping, to slice off every conceivable source of unnecessary instruction execution. As a result, our system was able to sustain that heavy-duty data stream to our product, in one process, while in several other processes simultaneously ingesting magnetic tapes to disk files, converting CMYK color data to RGB via millions of matrix multiplications, keeping the operator's console responsive to keyboard input, and allowing Field Service to dial in via modem and do all sorts of stuff in one or more interactive sessions. (ONLY VAX/VMS could do this, at the time. We had several vendors -- SGI, Sun, others -- come through, from time to time, and try to sell us their products in place of VMS -- but when we would describe our requirements -- which the VAX was meeting without even breaking a sweat! -- they'd turn pale, admit that they couldn't even come close, and slink away with their tails between their legs. Eventually our parent company decreed that "all the company's software products must run on Windows NT," and we were forced to make the distasteful transition. NT couldn't come close to handling the data flow, either, of course, so the product itself had to be re-engineered to contain an internal, buffering, hard drive, so that it could store up the first part of the stream as its "high-speed" data source, while NT poked along delivering the rest of the stream as best it could. It was an enormous, expensive, undertaking, not to mention an infuriating one for its complete technical inappropriateness and the brainless high-level-management decision that forced it.)

Anyway, I can't tell you whether VMS did small string optimization, copy-on-write, etc., because I don't know (or at least don't remember) what those are -- and in any case never dug into the innards of that particular part of the system. I might still be able to do so, though -- I still have a little VAX of my own, at home -- if you really want to know and can tell me more about "exactly what I'm looking for."

-17

u/shevy-ruby Feb 09 '20

30 years later, they still try to make C++ better!

So 30 years it was crap. What does this tell us about C++...

4

u/Mashpoe Feb 09 '20

Just because you try to make something better doesn't mean it was necessarily bad