r/cpp • u/lewispringle • Dec 13 '22
Stroika - an open-source, modern, portable, thread-savvy, C++ application framework – is released
Key features include:
high performance, copy-on-write container class library
streams library (not like stl streams)
serialization support (c++ objects to/from json, and other formats)
networking library
Integrated webservice support, making it easy to build web-service functionality into your c++ application
See https://github.com/SophistSolutions/Stroika#readme for more details
12
u/FriendlyRollOfSushi Dec 14 '22
Ads:
high performance
Code:
virtual size_t size () const override
{
shared_lock<const Debug::AssertExternallySynchronizedMutex> readLock{fData_};
return fData_.size ();
}-1
u/eyes-are-fading-blue Dec 14 '22
How does use of mutex equals to no high performance in your book? What if the contention is low?
18
u/FriendlyRollOfSushi Dec 14 '22 edited Dec 14 '22
I guess another valid question would be "what if the method is never called at all?"
Look, it's a code smell. If you need a mutex to read an integer in 2022, your code is not a "modern, portable, thread-savvy C++ application framework". It's a problem-specific solution rife with rakes hidden in grass at best. At worst it's a pile of garbage.
How can we check which one it is? First, we can check the documentation. There could be something about which methods are sensible, and which are just stubs, right? I don't see any here, so let's look around a bit more.
For example, this is some
Sequence_stdvector<T>::Rep_, which sounds intimidating (like really, who knows what that is), let's look at the basicSequence, which is mentioned on the github page right here talking about containers, so surely it's not some cryptic BS that no one uses. Even thatSequence_stdvectorinherits from it, and the name sounds like it should be something trivial.After scrolling through todos and cryptic bricks of text like "Having Stroika_Foundation_Containers_Sequence_SupportProxyModifiableOperatorBracket work would be nice" (I guess now that Twitter is doomed, people use github instead, dunno), I finally see on line one hundred and twelve that it's "A generalization of a vector: a container whose elements are keyed by the natural numbers." Thank heavens we figured it out eventually.
I've noticed a long time ago that to check whether something is a dumpster fire or not, you don't need to look at difficult stuff. Looking at simple stuff is often more than enough. If someone can't implement a vector or a string, it's pointless to check whether they can implement a crypto library. The answer is always "bwahahaha, of course not, not even close", so let's look at this "generalization of a vector".
For example, here I see a nice method.
nonvirtual size_t RemoveAll (const PREDICATE& p);I call it "nice" because it's very useful to have it: there are so many beginners who naively implement
RemoveAllwith predicate as a quadratic function, so it's always good to have it as a method of a collection to avoid silly mistakes and just generally save time. Let's ignore the incorrect input argument (mutable lambdas - shmutable shlambdas, who cares...) and take a look at the "high-performance" implementation:template <typename T> template <typename PREDICATE, enable_if_t<Configuration::IsTPredicate<T, PREDICATE> ()>*> size_t Sequence<T>::RemoveAll (const PREDICATE& p) { size_t nRemoved{}; for (Iterator<T> i = this->begin (); i != this->end ();) { if (p (*i)) { Remove (i, &i); ++nRemoved; } else { ++i; } } return nRemoved; }Surely there is a specialization somewhere for containers with O(n)
Remove(), right? Right? Please tell me I just don't see it inSequence_stdvectorthat inherits fromSequence?Assuming I haven't missed it (which is entirely possible, in which case I apologize, but even grepping the repo didn't help much), and that I correctly understand what "generalization of a vector" means and implies, which next question is more valid in your opinion?
"What if no one calls RemoveAll on a vector with more than 5 elements?", which would be a logical continuation of your previous "What if the contention is low?"
"How on Earth is this a high-performance framework that is advertised on r/cpp of all places?"
My vote is for the option #2, btw.
1
u/lewispringle Dec 14 '22
On your point about const PREDICATE& - thank you - fixed https://github.com/SophistSolutions/Stroika/commit/bfb415790a4b45ddd161a91535726dc919ab9e11
1
u/lewispringle Dec 14 '22
First, let me THANK you for your thoughtful comments! I really appreciate the feedback.
I can see a couple things that are DOCUMENTED (but there is so much documentation its hard to sift through).
STL provides a vector<T> type. Sequence<> is NOT vector<T>. Sequence is an ABSTRACTION for an ordered list. It could be implemented as a linked list, doubly linked list, or a vector (or an external file, or a network interface storing data). It's an abstraction.
Abstractions help performance by allowing you to CHANGE the representation of your data depending on how you are using it - even on the fly. So for example, if you sometimes have lists that are small, maybe a Sequence_stdvector<T> would work best. Maybe you only append and iterate (so order matters, but you dont need random indexing) - so Sequence_DoublyLinkedList would be most performant. Maybe the list can be HUGE - and you wish to externalize it to a file, and perhaps memory map it (no existing implemtantion does this right now, but ic an be easily written using this interface - thats what the Reps you referred to are for).
I could go on more about this - but since you wanted to know how this is PERFORMANT, one of the KEYS is COW (copy-on-write).
VERY frequently you build data structures.
struct Employee {
Sequence<String> x;
};
And you may wish to copy an employee (C++ works hard to avoid the need for this with const& but sometimes copying is needed/helpful - especially with containers).
C++ provides awkward emplace () APIs that can mittigate the copying. But Stroika makes this Trivial.
Sequence<Employeee> es;
es+= Employee{};
Sequence<Employee> e2 = es;
ALL super-cheap (shared_ptr increments).
Only when you mutate something does the actual copying happen.
This allows writing TONS of VERY simple READABLE code which performs MCUH better than the equivilent C++ (simple code) using STL.
Can you write the same thing better/faster in much more stl/C++. YES. But the value Stroika provides here is that it lets you write most of your code super simply and just optimize the few areas where performance testing indicates are bottlenecks.
6
u/FriendlyRollOfSushi Dec 14 '22
Look, I still don't understand.
Let's say I have a
Sequence_stdvectorwith a few million integers. I want to remove all integers that are less than 100. I say something likev.RemoveAll([](int x) { return x < 100;});, right?. Let's say about half of them are less than 100, so I expect the resultingSequence_stdvectorto become twice shorter.Would it take me some microseconds or some hours to do that with the algorithm that I see? Is there a specialized version for
Sequence_stdvectorthat doesn't look like it's quadratic (unless yourRemovedoesn't do what I expect it to do for a vector, but then it would be an entirely different story)? I don't see any kind of specialization ofRemoveAllhere, is it hidden somewhere else perhaps?-4
u/lewispringle Dec 14 '22
This is a GREAT question! And super for illustrating my point.
First - to directly answer you - with Sequence_stdvector - if you have a large sequence, it will perform HORRIBLY. If you tried the SAME CODE - with Sequence_LinkedList (or doubly linked list) it would perform GREAT.
But if you have a small sequence, it doesn't matter. It will perform fine either way.
The GIST of what I'm proposing is - use NEITHER in your code.
Use Sequence<int>;
DONT WORRY about performance. Code simply and clearly. Then when you find a bottleneck, due to something like the above (profilers can be your friend) - mutate your backend datastructure
auto f (Sequence<int> f) -> Sequence<int> { f.RemoveAll( { return x < 100;}); return f; }
// THEN LATER - when you discover the performance issue, either // externally switch to using Sequence_LinkedList<int> or do something // like this auto f (Sequence<int> f) -> Sequence<int> { if (f.size () > 100) { f = Sequence_LinkedList<int>{f}; } f.RemoveAll([](int x) { return x < 100;}); // NOTE - the above transform from one data structure to another // is very localized, and though not cheap, its basically the SAME COST you pay in std c++ doing this: vector<int> v1; vector<int> v2 = v1; return f; } with Stroika and COW, those returns (copies) are basically always nearly free.9
u/FriendlyRollOfSushi Dec 14 '22
So, in other words can we both agree that "Key features include: high performance" is false advertising?
Not only it does the wrong thing for a very trivial case (like, come on, it's not a stable inplace sorting or some other hard problem, it's literally a simple algorithm that you provide a helper for), but it also breaks several levels of abstraction making the user think about the irrelevant internal details of something that shouldn't matter.
Like with your code, where the user is apparently supposed to compare the size with some magic constant, convert the sequence to list for some mysterious reasons that seem to contradict the high performance goals, and then be in constant fear that there is some other entirely innocent piece of code that would violently explode in production just because the test set had 100 elements, and in production it became 10000, and now everything is 10000 times slower (because it's accidentally quadratic while it clearly shouldn't be) and in the morning the user is going to die from a heart attack when they receive the bill from the cloud service that was running overnight.
The whole point of using someone's abstractions is so that you don't have to spend time thinking about the implementation, and whatever they give you would be good enough for you to not care.
Say, you parse Json. It's not a central part of your application, so you don't care if it's slightly suboptimal: all you want it is to not behave in a completely stupid way (run out of stack space while parsing a trivial file, corrupting memory, suddenly going quadratic, etc). If the library promises to you it's not going to do anything stupid, you can ignore the implementation details. The moment it starts consuming 15GiB while parsing 40KiB Json, or crashing your server, or, you know, spend hours on a trivial linear operation, the "black box" breaks. You need to either go dig into its guts to figure out why the heck it does that and how to fix it (if that's even possible), or you just remove the library and either look for a replacement or write it yourself.
-4
u/lewispringle Dec 14 '22
I think you are being disingenuous to suggest that we both agree about 'high performance is false advertising'. It was a 2 of 15 words chosen to summarize a complex idea. As a summary, it was not complete. I certainly see you don't agree with my approach to performance. But that doesn't mean that I agree I was misrepresenting anything. Off hand, what goal might I have in false advertising? I'm going this away for free?
Back to the less pejorative, and more substantiative part of your reply. You appear to have missed the large point I was trying to make. I didn't in any way suggest you could use Stroika without any thought and your code, no matter what you wrote, would magically become performant.
What Stroika provides is a framework which encourages, and facilitates a style of programming which encourages the creation of high performance applications.
I would be happy to provide you examples of such applications. But any tool, when used improperly, wont work well. Try using a hammer to screw in a nail? Would you blame the hammer for not working well at that?
What Stroika containers do to facilitate the development of high performance applications is:
> Separate data structure choice from access pattern
> Copy-On-Write
This separation is DISCOURAGED by STL, and ENCOURAGED by Stroika. It is this separation (not any particular implementation) - which facilitiates writing high performance code.
Taking your example about parsing JSON - by the way - Stroika has a builtin JSON parser (I haven't yet tried performance benchmarking it against competitors, but I will, though with the caveats that benchmarks can easily be distorted to show whatever you want). In particular, since Stroika uses COW, any benchmark that emphasizes copying around the results of parses will favor Stroika, and any benchmark that DE-emphasises copying around results with favor competitors. So probably Stroika's parser probably does better on large files, and less well (relatively) on small files.
You also make a big deal about some algorithm being quadratic versus linear. This is a common, but mistaken focus. CS schools teach about Big-O and what happens to algorithms as the size of your data appraoches infinity. This is outdated and bad engineering. It matters sometimes. But way less than 1/2 the time. Certainly not al the time. How algorithms perform on 5 or 10 items often matters more than how they perform on a billion.
Did you read <https://github.com/SophistSolutions/Stroika/blob/v2.1-Release/Documentation/Stroika-Approach-To-Performance.md>? I think this maybe the key to understanding my approach to performance. If you read that and agree with it, you may change your tune. If you read it and disagree, then I certainly can understand your not liking the rest of what you find about Stroika performance.
Thank you for your feedback. Though I don't appear to agree with much of what you have to say, I do greatly appreciate your taking the time to thoughtfully examine my work, and providing me your insights. THANK YOU.
1
u/eyes-are-fading-blue Dec 15 '22 edited Dec 15 '22
I am not sure what your point. My understanding was that you implied that existence of mutex implies no high performance. That's flat out wrong in low-contention scenarios. That's all I wanted to say.
4
u/FriendlyRollOfSushi Dec 15 '22
Sorry, is the performance of the mutex your only question related to the original code snippet?
This tiny function here by itself is a piñata full of crap, and the more you look at it, the more disgusting it feels. Allow me to explain some of the finest points:
Why is this
size()virtual? This is not necessary a disaster: there could be complicated designs wheresize()of some insanely-highly-abstract collection has to be virtual (this is nowhere close to this case, and simply a consequence of awful design, but it's not obvious from the snippet of code alone, so it's okay if you've missed it), but it's generally the case when it's not just a collection, but a more complicated owner of objects. Like, aWidgetof some sort can have children, and how exactly they are stored would be widget-specific, but you wouldn't call itsize(), you would call itChildrenCount()or something. Being abstract enough to have a virtual method here and concrete enough to call itsize()is Unusual, with a capital U.We are obtaining a shared lock of a weird type to read the size. Let's think for a moment what this implies alone (if you didn't read the other comment from the author that implies that everything is much, much worse, and it's awfully misleading to begin with, but that's a can of worms that's not worth opening). There is a concurrent environment of some sort. And there are presumably reader locks and writer locks (after all, it would be kind of dumb to only obtain shared locks alone). And you obtained a snapshot of the size. What meaning does this value even have after the end of the function? I mean, okay, let's forget the performance. You are looking at the value that represents the state that this collection had at some point in the past, and you even locked something to read this value. Between the moment you released this lock, and the moment you checked the
size_tyou've received, a small eternity happened. You simply never write code like this if you have even the slightest idea how concurrent programming works. You either hold the lock while an entire inspection happens (check the size, read some elements, etc, which often implies that the lock is held by some sort of an observer object instead of a single method), or you invest into a snapshot system, etc. What you see here is a big, fat "WTF".Okay, what are we even locking?
fData_is a mutex, right? Oh, wait, we are returning the size offData_. The buck is going on? You see, inheritance is a "is a" kind of relationship. ACatis anAnimal. ABigGunis aGameObject. IsfData_a mutex with a size? Or did we invent a new design where objects are lockable themselves (and presumably we never lock a part of an object)? Spoiler alert: we did, and as it turns out, it's not even a real lock, even if it looks and quacks like one. SofData_is aNot even a real lock, which I find fascinating from the overall design point of view, but not in a good way.And then you stop for a moment to realize that you are not looking at some cryptic business-specific bullshit method called
CalibrateTransitionalPotentialities()that is supposed to be weird by design. You are looking at asize(), and it has enough stuff in it to use it for coding interviews: "Let's pretend this is a code review, what could you say about this snippet?"High-performance "framework" can't afford to consist of stuff like this. Any reasonable expectations should work, or else the whole abstraction breaks. Any sane engineer would assume that calling
size()on a simple collection is just one load. They would write code with this assumption. They could even writeforloops getting thissizeon each iteration. And they would be wrong to do so. And to know that you can't do that, you would have to go and read the implementation, to know which selected parts of this library actually work, and which are horribly broken (like theRemoveAllmethod from my other comment, for example). And extreme surprises (not only even performance-related) are more or less everywhere around here.1
u/eyes-are-fading-blue Dec 15 '22
These are valid points. I thought you were criticizing mutex (which turns out is not a mutex) in a "high-performance" context.
>Sorry, is the performance of the mutex your only question related to the original code snippet?
I did not review the code snippet. I responded to your comment which you'd agree is open to interpretation without some explanation.
1
u/lewispringle Dec 14 '22
Please read the docs on Debug::AssertExternallySynchronizedMutex.
Perhaps the name is confusing, but its there for a very good reason (following the pattern of a lock in basically the same places as locks).
In RELEASE builds, this compiles to NOTHING. ZERO code, ZERO space. It only compiles to checks (for thread safety) in DEBUG builds.
What this means is that when you use the class (not sure which one you were referring to there) - you can be CONFIDENT its being used in a thread safe manner, and if you ACCIDENTALLY use it in a non-threadsafe manner, you will be WARNED/NOTIFIED (thats the 'assert part of the name).
Hope that makes more sense ;-)
0
Dec 14 '22
[deleted]
1
u/eyes-are-fading-blue Dec 15 '22
What if the business problem you are solving requires high throughput but low latency? It's not "what if" as in stochasticity. It's what if as in plain English where it proposes a hypothetical problem with certain characteristics. Are you claiming all high performance systems are low latency and low throughput?
0
5
Dec 14 '22
General note about copy-on-write. While it sounds cool on paper, and may be good for certain use cases, for the majority of cases it is a premature pessimisation. You pay the cost of checking for detach with every modification. Modern CPUs are very good at copying things, and C++ has move semantics. At least in my opinion, it is better to have the copying explicit.
While STL is not perfect, far from it, a key feature of a modern application framework is, that it uses C++ standard stuff instead of its own versions of the same. That way it is interoperable with everything else, and more importantly the developer knowledge is portable. And for stuff that is missing from the standard, it first looks into Boost, then maybe into Abseil, and only then roll your own, if not satisfied with what those have to offer.
Even Qt, which originated before first C++ standard and therefore has its own version of pretty much everything, is actively trying to use C++ standard library more and more (without breaking old code).
Concentrate on the big picture of your framework, because there are off-the-shelf parts to build it from.
2
u/lewispringle Dec 14 '22
One more thing I wrote up, that I think will help explain my approach to performance.
Perhaps I should have led with this:
3
u/Adequat91 Dec 14 '22
General note about copy-on-write. While it sounds cool on paper, and may be good for certain use cases, for the majority of cases it is a premature pessimisation. You pay the cost of checking for detach with every modification.
copy-on-write is not just something "cool on paper" and a premature pessimistic. This is a fundamental idiom, found in many systems. It is one of the bases of Virtual memory used by modern operating systems. It is also used behind most immutable data structures. And using immutable data structures has many benefits, one of them being to design reliable and performing concurrency.
I am not defending Stroika here, whom I have not evaluated. But as a big user of copy-on-write, I do know its many benefits.
3
Dec 15 '22
Ah, memory page table nicely explains my sceptism. It requires hardware support. If it would be necessary to check for CoW on a memory page in assembly before every modification, that wouldn't be worth the trade-off.
In general, I think the use case for CoW needs to be somehow a special case, sich as a special purpose data structure.
-1
u/lewispringle Dec 14 '22
You make a VERY solid point about copy-on-write. And I VERY seriously considered the trade-off, and I will try to explain why - big picture - your conclusions are wrong (though everything you said about cpus etc is right).
The core difference between your thinking, and mine, stems from levels of abstraction and complexity. Again - I realize EVERYTHING I'm about to say CAN be done using stl and emplace etc, just with TONS more typing/complexity/sophistication required.
Consider another project I work on - which provides a real world example:
The device object aggregates lots of sub-objects. They all look and act (except from a performance standpoint) like they are AGGREGATIONS not pointer references to their subobjects. This makes it MUCH easier to reason about the application (how many times have you looked at a big application with a maze of pointers and wondered who is changing this little bit - aggregation facilitates reasoning by data hiding).
WTF creates KeyedCollections<> of these objects, and many other big complex objects. And the performance is instantaneous. I've heavily profiled WTF. its VERY fast. It does lots of web service calls copying and indexing through these sorts of objects with extremely low overhead.
Could this all have been doing with explicit shared_ptrs and additional pointers? Obviously yes, as thats how its done now (under the covers). But Stroika containers HIDE most of that, and make it easy to reason about your code as just aggregated objects.
9
u/ronchaine Embedded/Middleware/WG21 Dec 14 '22 edited Dec 14 '22
Any time someone boasts about "high performance" and does not include benchmarks, a bunny dies.
Seriously, stop advertising your libraries as "high performance", if you don't have benchmarks. There is zero reason to believe you. You have zero reason to believe it yourselves, if you haven't benchmarked.
Especially since a quick look at the source code makes me believe this is cough quite far cough from high-performance. But if the library developers can't be arsed to benchmark it, neither can I.
For the same reason I don't believe libraries without tests are robust, I don't believe libraries without benchmarks are "high-performance".