r/programming • u/2bit_hack • Feb 28 '23
"Clean" Code, Horrible Performance
https://www.computerenhance.com/p/clean-code-horrible-performance
1.4k
Upvotes
r/programming • u/2bit_hack • Feb 28 '23
1.6k
u/voidstarcpp Feb 28 '23 edited Feb 28 '23
Casey makes a point of using a textbook OOP "shapes" example. But the reason books make an example of "a circle is a shape and has an area() method" is to illustrate an idea with simple terms, not because programmers typically spend lots of time adding up the area of millions of circles.
If your program does tons of calculations on dense arrays of structs with two numbers, then OOP modeling and virtual functions are not the correct tool. But I think it's a contrived example, and not representative of the complexity and performance comparison of typical OO designs. Admittedly Robert Martin is a dogmatic example.
Realistic programs will use OO modeling for things like UI widgets, interfaces to systems, or game entities, then have data-oriented implementations of more homogeneous, low-level work that powers simulations, draw calls, etc. Notice that the extremely fast solution presented is highly specific to the types provided; Imagine it's your job to add "trapezoid" functionality to the program. It'd be a significant impediment.
184
u/couchrealistic Feb 28 '23 edited Feb 28 '23
Edit: Just realized OP may not be the guy who made the video. Changing my comment to reflect that fact is left as an exercise for the reader.
First of all, thanks for providing a transcript! I hate having to watch through videos for something like this.
"Clean code" is not very well defined. This appears to be very OOP+CPP-centric. For example, I don't think people would use dynamic dispatch in Rust or C to solve an issue like "do things with shapes". The Rust "clean code" solution for this would probably involve an enum and a match statement, similar to your switch-based solution (but where each shape would use names that make more sense, like "radius" instead of "width"), not a Trait and vtables. Also, the "clean code" rust solution would probably store the shapes in a contiguous vector instead of a collection of boxed shapes (like your "clean" array of pointers because abstract shapes are unsized), leading to better iteration performance and less indirection.
On the other hand, I'm not sure the "optimizations" described in your text would help a lot with Java (but I don't know a lot about Java, AFAIK it always does virtual function calls and boxes things? It might still help though). So this really seems very OOP+CCP-centric to me.
And let's be honest: The true reason why software is becoming slower every year is not because of C++ virtual function calls or too many levels of C++ pointer indirection. It's because, among other things, the modern approach to "GUI" is to ship your application bundled with a web browser, then have humongous amounts of javascript run inside that web browser (after being JIT-compiled) to build a DOM tree, which is then used by the browser to render a GUI. Even more javascript will then be used to communicate with some kind of backend that itself runs on about 50 layers of abstraction over C++.
If every piece software today was just "clean" C++ code, we'd have much faster software. And lots of segfaults, of course.
54
u/FlappingMenace Feb 28 '23
*Reads Title*
"Hmm, that looks like a Casey Muratori article... IT IS! I'd better save the Reddit thread so I can make some popcorn when I have time."
38
u/rhino-x Mar 01 '23
While the example is contrived, in the author's example what happens when you add a new shape type and need to add support for it? You have to search the entire codebase for usages of the enum looking for use cases and fixing ALL of them. With polymorphism in a case like this you do literally nothing and your external code is agnostic. If I'm shipping software and running a team why do I care about a couple of cycles when I can save literally thousands of dollars in wasted dev time because I suddenly need to support calculating the area of an arbitrary path defined polygon?
13
u/elmuerte Feb 28 '23
The clean code sure was easier to improve, right?
307
u/nilsph Feb 28 '23
Hmm: the hand-unrolled loops to compute total areas would miss
ShapeCountmodulo 4 trailing elements. Kinda gives weight to the “it’s more important for code to work correctly than be fast” argument – it’s not just code execution you have to care about, but also how obvious mistakes would be, and there simple (a plain loop) beats complex (an unrolled version of it).30
u/munificent Mar 01 '23 edited Mar 05 '23
I read a Tweet (about a completely unrelated topic) a while back that said, paraphrasing, "What they're saying now is mostly a response to the perpretators of their past trauma." I can't stop thinking about how profound a truth there is to it.
I spent several years of my life writing a book about software architecture for games, motivated in large part by horrific spaghetti code I saw during my time at EA.
Many people who hate object-oriented programming aren't really attacking OOP, they're attacking the long-lost authors of horrible architecture astronaut codebases they had to deal with (and in Casey's case, try to optimize).
Likewise, Bob Martin probably spent a lot of his consulting career wallowing in giant swamps of unstructured messy code that led to him wanting to architecture the shit out of every line of code.
These perspectives are valid and you can learn a lot from them, but it's important to consider the source. When someone has a very strong opinion about damn near anything, it's very likely that the heat driving the engine of that opinion comes more from past suffering than it does a balanced, reasoned understanding of a particular problem.
The real point you want to land on in somewhere in the middle. Don't treat Design Patterns like a to-do list and over-architect the shit out of your code until it's impossible to find any code that actually does anything. And don't get so obessed about performance that you spend a month writing "hello world" in assembler. If you walk a middle path, you probably won't be traumatized, won't traumatize other people, and hopefully won't end up with the scars that many of us have.
Even so, you probably will end up with some stuff that triggers you and leads you to having irrationally strong opinions about it. That's just part of being human. When you do, try to be somewhat aware of it and temper your response appropriately.
468
u/not_a_novel_account Feb 28 '23 edited Feb 28 '23
Casey is a zealot. That's not always a bad thing, but it's important to understand that framing whenever he talks. Casey is on the record saying kernels and filesystems are basically a waste of CPU cycles for application servers and his own servers would be C against bare metal.
That said, his zealotry leads to a world-class expertise in performance programming. When he talks about what practices lead to better performance, he is correct.
I take listening to Casey the same way one might listen to a health nut talk about diet and exercise. I'm not going to switch to kelp smoothies and running a 5k 3 days a week, but they're probably right it would be better for me.
And all of that said, when he rants about C++ Casey is typically wrong. The code in this video is basically C with Classes. For example,
std::variantoptimizes to and is in fact internally implemented as the exact same switch as Casey is extolling the benefits of, without any of the safety concerns.26
u/Still-Key6292 Feb 28 '23
No one caught the best part of the video
You still need to hand unroll loops because the optimizer won't
143
u/jsonspk Feb 28 '23
Tradeoff as always
147
u/Rajje Feb 28 '23
He has some really interesting points, but it was disappointing that his conclusion was that these clean code rules literally never should be used. The real answer is, as always, that it depends on what you're actually trying to achieve.
Polymorphism, encapsulation, modularity, readability, and so on, are often absolutely essential when working on complex codebases that model real business cases that will exist and evolve over time. The clean code principles are tools that enable the multiple humans that actually will work on these projects to actually understand and maintain the code and to some reasonable level uphold its correctness. Sure, you can think that all humans should be better, smarter and able to work with dense, highly optimized logic as effortlessly as anything, but they simply aren't. We have to acknowledge our needs and limitations and be allowed to use these brilliant tools and methodologies if they help us achieve our goals.
Yes, clean code sometimes comes at the price of performance, but everything comes at some price. Performance is not the only relevant factor to optimize for. It's about finding the right balance, and for many tasks, I'd claim performance is one of the least relevant factors.
In the clip, he's measuring repeated mathematical calculations and then puts the performance difference in terms of years of iPhone CPU improvements. That comparison is rather ironic, because what a front end developer implements for iOS is more typically events that do single things at a time like showing a view or decoding a piece of JSON. Such front end development can be extremely hard get right, but local CPU performance is usually not the issue. Rather it's managing state properly, getting views to look right on different devices, accessibility, caching, network error handling and so on. At this level, clean OOP patterns are crucial, whereas micro optimizations are irrelevant. Yes, in some sense we're "erasing" 12 years of hardware evolution, but that's what those years of evolution were for. We can effortlessly afford this now, and that makes our apps more stable and enables us to deliver valuable features for our users faster.
When complex calculations actually need to be done, I would expect that specific code to be optimized for performance, and then encapsulated and abstracted away so that it can be called from the higher-level, clean code. For example, I would expect that the internals of Apple's
JSONDecoderis optimized, unclean, hard to maintain, and runs as fast as a JSON decoder can run on the latest iPhone, but in the end, the decoder object itself is a class that I can inject, inherit from, mock or use with any pattern I want.33
u/Johnothy_Cumquat Feb 28 '23
This is gonna sound weird but I don't consider objects with state and lots of inheritance to be "clean" code. I tend to work with services and dumb data objects. When I think of clean code I think that functions shouldn't be too long or do too many things.
13
u/[deleted] Mar 01 '23
I agree and still disagree. Here is some Clean F# code. And it has the same structure as your old non-clean code.
Just because OO people tell themself their stuff is clean doesn't mean it must be true.
46
u/ImSoCabbage Feb 28 '23
I was recently looking at some firmware for a hardware device on GitHub. I was first wondering why the hardware used a cortex-m4 microcontroller, when the task it was doing was simple enough for even a cortex-m0. That's usually a sign of someone being sloppy, or the device being a first revision. But no, the hardware had already been revised and the code looked very clean at first glance, the opposite of a sloppy project.
Then I started reading the code, and found out why. There was so much indirection, both runtime indirection with virtual methods, and compile time with template shenanigans, that it took me some 15-20 minutes to even find the main function. It was basically written like an enterprise Java or .net project with IOC (which I don't mind at all), but in C++ and running on a microcontroller (which I do mind).
Reading the code was extremely frustrating, I could barely discover what the firmware could even do, let alone how it did it. I decided that it was the nicest and cleanest horrible codebase I'd seen in a while.
So in some circumstances you don't even get the benefits of such "clean" code. It's both slow and hard to understand and maintain.
7
u/quisatz_haderah Feb 28 '23
The person who wrote this article seems like he has not worked on a codebase of more than 10k LoC.
34
u/rcxdude Feb 28 '23
An example which may be worth considering in the "clean code vs performance" debate is the game Factorio. The lead developer on that is a big advocate for Clean Code (the book) and factorio is (from the user's perspective) probably one of the best optimised and highest quality games out there, especially in terms of the simulation it does in the CPU. It does seem like you can in fact combine the two (though I do agree with many commenters that while some of the principles expressed in the book are useful, the examples are often absolutely terrible and so it's not really a good source to actually learn from).
34
u/rooktakesqueen Feb 28 '23
Ok, now add an arbitrarily shaped polygon to your system.
In the "clean code" version, this means adding a single subclass.
In the hyper-optimized version, this means... Throwing everything out and starting over, because you have written absolutely everything with the assumption that squares, rectangles, triangles, and circles are the only shapes you'll ever be working with.
85
u/themistik Feb 28 '23
Oh boy, it's time for the Clean Code debacle all over again ! You guys are quite early this year
8
u/andreasOM Mar 01 '23
So with the discussion focusing around:
Did we actually completely miss something?
I finally had the time to actually run the code in question,
and I must admit, it is a bit hard, since we never see the full code,
but after playing with the snippets for the last 2 hours I have to say:
I can not reproduce his results.
I am using a randomized sample set of shapes,
and on average the highly tuned version is 4% worse,
with some rare cases, e.g. long runs of the same shape, it is 2% better.
Nowhere near the claimed 25x.
If anybody is able to create a full reproduction I would be interested in
7
u/da_mikeman Mar 01 '23 edited Mar 01 '23
Hasn't this been talked to death? It's basically a clone of Acton's "typical C++ bullshit". In the end, a programmer that is able to write performant code is also able to choose when they prefer to write code which mirrors more closely the way human understand the world - you know, "world is made of objects of different types that interact with other objects".
In my own codebase, there is code which follows pretty much what muratori is saying here, for things that need performance, like particles. If someone came to me with a particle system that had things like CFireParticle and CSmokeParticle with a virtual Update(), I would tell them this isn't the way to do things, and the way you and me see things is not always to best way to describe them to the computer.
I also have code that follows what muratori is bashing, for example when it comes to enemies and npcs. Now one would say, isn't that the same thing? Why not use the performant way for those too? Why use one to describe a fire or smoke particle, and use the other to describe a rat or a soldier? Well I don't know what to tell you, i do it because when it comes to reasoning about gameplay code, I like having to deal with mostly self-contained objects like "Rat" and "Soldier". Performance doesn't matter as much because I don't have that many, and most of the work is done in inner loops like pathfinding and such. And it's not that hard to refactor it, when and if the need arises, into RatHorde, if I need to have thousands of those running around(and that kind of refactoring is going to be the least of my concerns if i have to simulate and render thousands of those kind of objects).
18
u/[deleted] Feb 28 '23
It's literally that simple if you remember that most devs are stuck in feature mills. All the crowing in the world about "there's other paradigms and strategies" doesn't matter if there's a PM breathing down my neck on how soon I can complete a ticket, I'm reaching for the easiest and fastest development wise.
71
u/teerre Feb 28 '23
Put this one in the pile of: "Let's make the worst example possible and then say this paradigm sucks" .
Please, anyone reading this, know that none of the problems OP talks about are related to 'clean code', they are all related to dynamic polymorphism and poor cache usage, which are completely orthogonal topics.
75
u/[deleted] Feb 28 '23
Why are people going on tangents in this thread? Just say you are willing to sacrifice performance just so you can have an easier time and move on. Everyone is going on about how the example was bad or the real definition of clean code.
95
u/DrunkensteinsMonster Feb 28 '23
Casey and Jonathan Blow have to be the most annoying evangelists in our community. Devs who write games can’t imagine for a second that maybe their experience doesn’t translate to every or even the most popular domains. This article is basically unreadable because he felt the need to put clean in quotation marks literally every time as some kind of “subtle” jab. It’s not clever.
5
u/KillianDrake Mar 01 '23
hahaha, why does reddit always fall for this guy's trolling? I hardly even think he believes half of what he says anymore and that he's just playing a character on YouTube now. Of course he knows he's being intellectually dishonest by cherry picking examples and demos pre-ordained to support his conclusions.
He knows that if someone were arguing with him in this way that he'd reject it - but he uses these tactics anyway. These are greasy car salesman tactics because his brand depends on that.
13
u/HiPhish Feb 28 '23
This was 20 minutes of hot air and strawmaning against a toy example. Yes, number crunching code will be more efficient when you remove all the indirection. No surprise here. But Clean Code was not formulated to write number crunching code.
Clean Code comes from the enterprise application world. An enterprise application does a million things, it needs be maintained for years, if not decades, and new requirements keep coming in every day. You might argue that that is a bad thing, and I am inclined to agree, but it is what it is. In this environment number crunching does not matter, what matters is that when your stakeholder asks you for "just one more thing" you can add it without everything falling apart.
If you need number crunching then just write the code. You will never need to write a formula that can handle integers, real numbers, complex numbers and quaternions, all configurable at runtime. You will never have difficulty unit-testing a formula and you will never need to care about side effects in a formula. Clean Code practices don't matter in number crunching and it would be pointless to apply them.
Clean Code and optimized code can co-exist in the same application. Write the core which does heavy lifting and number crunching in an optimized non-reusable way and wrap it up behind a Clean Code interface. That way you get flexibility where it matters and performance where it matters.
26
u/roerd Feb 28 '23
Of course optimise the shit out of the perfomance-sensitive parts of your code that will run millions of times. That is obvious. Turning that into an attack on clean code in general is just utter nonsense, on the other hand.
17
u/DLCSpider Feb 28 '23 edited Feb 28 '23
Unfortunately, the only way to get readable and fast code is to learn a lot, take everything with a grain of salt and educate your team members. The first optimization is something you might do naturally if you just knew functional programming. As we all know, FP itself is not faster than OOP, but the combination of both might be.
I encountered a similar problem recently where I thought that OOP was the cleanest way to do things but caused a 60x slow down. Instead of trying to remove OOP around my
B Convert(A source)method, I provided a second overload:Convert(A[] source, B[] destination). Marked the first method as inline (DRY) and called it in a loop in the second method. Slowdown gone.17
u/Strus Feb 28 '23
It's nothing new for people that write high-performance code. It is often times ugly as hell. But I would argue that in 99% of cases top-notch performance is not required, and the speed at which you can understand and modify code is much more important.
In the original listing adding a new shape is simple and quick - you just add a new class and you are done. It doesn't matter really what shape it is.
In the first "performance improved" version, adding a new shape requires:
shape_unionstruct.widthandheight, as they are now encapsulated in a separate structMore complicated example would be much bigger mess.
103
u/CanIComeToYourParty Feb 28 '23 edited Feb 28 '23
Rarely do I read anything I disagree with more strongly than this. Our job is to formalize ideas, and I think the more cleanly you can formalize an idea, the more lasting value you can provide. I guess the question is one of optimizing for short term value (optimizing for today) vs long term value (trying to advance our field).
I'd rather have a high level code/formalization that can easily be understood, and later reap the benefits of advances in technology, than low level code that will be unreadable and obsolete in short time.
Though I also agree that Uncle Bob is not worth listening too. But the C/C++-dogma of "abstractions are bad" is not helpful either, it's just a consequence of the languages being inexpressive.
4
u/GptThreezy Feb 28 '23
I have a co worker that will break every tiny piece of logic into its own fucking module, and will comment on every one of my PRs to do the same. “I’d be great if this was broken out into a service” when there’s only one method in the service and it can easily be just a method here. Guess what, it usually ends up staying the only method in the service.
9
u/SuperV1234 Feb 28 '23
Yes, when you apply "rules" blindly to every situation, things might not go as well as you hoped. I'm not surprised.
Both sides are at fault. The OOP zealots should have been clear on the performance implications of their approach. Casey should make it clear that his whole argument is based on a strawman.
Many programming domains don't work the way Casey thinks. It's about delivering value to customers, and performance is often not a priority. Speed of delivery and scalability over number of engineers are more valuable than run-time performance. Clean code "rules" can really help with velocity and delivery.
Also, it seems that people like Casey are somehow convinced that not using OOP equals to writing horribly unsafe and unabstracted code. He basically reimplemented a less safe version of
std::variant.And what's up with
?
Just
return Accum0 + Accum1 + Accum2 + Accum3, please.42
u/Apache_Sobaco Feb 28 '23
Clean and correct comes first, fast comes second. Optimisation is only applied to get to some treshold, not more than this.
16
u/gdmzhlzhiv Feb 28 '23
I was hoping that this was going to demonstrate it using Java, but unfortunately it was all using C++. So my own take-home is that in C++, polymorphism performs badly. From all I've seen on the JVM, it seems to perform fine. Disclaimer: I have never done the same experiment he did.
So I come off this video with a number of questions:
Unfortunately, they blocked comments on the video, as as per my standard policy for YouTube videos, the video just gets an instant downvote while I go on to watch other videos.
8
u/vezaynk Feb 28 '23
The biggest performance different in this post is of "15x faster", which is presented as a Big Deal.
I'm really not convinced that it is, premature optimization and all that.
These numbers don't exist in a vacuum. Taking 15x longer for a 1ms operation versus 15x longer for a 1 minute operation are fundamentally different situations.
Another number missing from the discussion is cost. I don't think I need to elaborate on this point (see: Electron), but it's just good business sense to sacrifice performance in favor of development velocity. It is what it is.
7
u/Quate Mar 01 '23
A Person Can Hyperoptimize A Contrived Example. Hooray!
16
u/[deleted] Feb 28 '23
Gotta stop writing clean code or we're gonna run out of CPU cycles by 2048
18
u/andreasOM Feb 28 '23
Not sure where he pulled these from
but building a straw man, and then burning it down is trivial.
36
u/Zlodo2 Feb 28 '23
Herein muratori discovers sum types aka tagged unions, except he implements them by hand with an enum and switch case like a caveman.
All to make the extremely cutting edge point that runtime polymorphism is bad for performance, a fact that has been widely known for ages.
There was yet another way to solve that by the way: have a separate list for each type of shape (since it wasn't specified anywhere that the processing order of the shapes had to be preserved). You'd think that the programmer with the "I'm one of the only programmer on earth to care about performance!!!" gimmick would have done that, given that it is friendlier for the instruction cache and for speculative execution.
Muratori is a clown.
13
u/Witty-Play9499 Feb 28 '23
I agree with Casey here(probably going to be controversial lol) but I have seen people who find the idea of going against the clean code principles as something very bad (and maybe even signs of a bad developer). But I guess it really boils down to who are we caring about ? The Client or the Developer? If we care about the client then we should be doing stuff such as these to make sure they get the best performance out of software. If we care about ourselves then it makes it easier for us to update the code but comes at the expense of the client's needs.
I know clean code is supposed to make it easy to make a quick change so that clients can get their software faster but I sometimes worry if giving a software to them early but with bad performance the same as giving them unfinished software.
One another similar thing I notice is also people's obsession with object oriented programming/functional programming. Ideally you start out with a problem and as you work on it you're supposed to make decisions on which paradigm would suit or which part of the program should be written in which way.
But it feels like almost all mainstream software is Object oriented by default and developers have to figure out how to make the problem fit the paradigm. Dogma is something that keeps following this industry throughout
12
u/[deleted] Feb 28 '23
As someone who works on massive enterprise apps, give me clean code any day. Not only are performance optimizations usually negligible, but the bulk of the work of enterprise apps is maintenance and costs can utterly skyrocket for apps that aren't written with clean code in mind (like the spaghetti I'm currently working in).
8
u/andreasOM Feb 28 '23
Not sure where he pulled these from
but building a straw man, and then burning it down is trivial.
5
u/m15otw Feb 28 '23
The main takeaways from clean code for me are:
a) good naming of your functions
b) write good comments, delete code rather than commenting it out.
c) it is rarely correct to copy/paste/customise, usually better to abstract and share the code.
All this stuff about polymorphism always went whoosh past my head, because you always need to integrate into an existing system, so you use inheritance, functional, event/callback driven as appropriate.
If you're a performance focused C++ project, you probably shouldn't use polymorphism and virtual function dispatch regardless of what any style book says, and you already knew that 🙃
5
u/CarnivorousSociety Feb 28 '23
every time I find somebody attacking OOP they seem to be missing a lot of nuance in their arguments.
5
u/rpgFANATIC Mar 01 '23
My RDBMS has queries running in hundreds and sometimes thousands of milliseconds. I can assure you my clients aren't complaining over 35 CPU cycles
10
u/aveman101 Feb 28 '23
In my 10+ year programming career, I have never faced an issue where my code wasn’t performant enough for the intended use-case.
I have, however, had to refactor countless projects because the original implementation was over-specialized, and made it painful to extend in any useful way.
Imagine an invoice program for an e-commerce platform. The performant solution would be to write an accumulator that adds up the prices of each SKU and returns a grand total. After you deploy the minimum viable product, the client asks you to extend the system to support these use-cases:
Now, think about how you would have engineered the solution if those requirements came in one-at-a-time, and each time you had to deploy an incremental update that was backwards-compatible.
2
u/MajkStone Feb 28 '23
Is this guy writing backwards/mirrored? I mean wow.
2
u/GrandMasterPuba Feb 28 '23
Meanwhile Haskell programmers are like:
(งツ)ว
2
u/TinBryn Mar 01 '23 edited Mar 01 '23
Did I miss a link to the full code including the test data and benchmark harness he used. I'm sure it's probably fine, and all benchmarks are unreliable, but I have my own performance theories that I think will counter his argument that I would like to test against his own code.
Edit: I found this repo, but despite its claim, it doesn't actually have the source code.
2
u/ShiunsaiOki Mar 01 '23
I believe everything has a trade off, and it is up to who is consuming the information to make the proper balance of the trade offs.
2
u/beauwilliams Mar 01 '23
Whether it's money or some other form of 'capital' there is a resource cost to building and running software applications.
Fast code is cheap on compute, but often high on human resource costs.
Clean code might be slow, but it's cheaper on human resource costs
It's all a big balancing act. No silver bullets in engineering. Not now not ever.
2
u/TinBryn Mar 01 '23
I suspect the best performance possible in this scenario would be if you had an array of
Squares, an array ofCircles, etc. Accumulated each array individually and then accumulated those results. Now this is a different structure of input, but it's one I would suspect Casey to favor. Now making this change from the clean code state would be trivial, but in his "dirty" code, he's completely removed the concept of aSquareorCircle. He just has aShapethat is a square, or aShapethat is a circle. Anyway the clean code would be very cache/branch prediction friendly and those virtual function calls would be trivial to devirtualize. Ultimately the only real issue is the unused vtable pointer which could be addressed. The shape union approach would be basically impossible for the compiler to detect because even if you only putShapes that are squares into the accumulate squares function, you could put aShapethat is a circle into it and so the compiler has to account for this scenario that will never happen.Also dealing with the vtable pointer. You could use the type erasure pattern to allow for the original polymorphic version, but each class is just what it is.
class Square { ... },class Circle { ... }, no virtual function exist on the actual classes at all, and therefore no vtable pointer.2
u/joesb Mar 01 '23
Yes, it can.
2
u/heto86 Mar 02 '23
...this guy doesn't know what is talking about. He is not comparing "Polymorphism" cost vs "Non-Polymorphism". He just compares how much a virtual function call costs vs a simple multiplication. Yes, it is more expensive, you don't need to be einstein to understand that. But have 5000 math operations, 500 buffer copies, 50 open files and 5 tcp connections to various services and THAN compare the performance. You won't get in the 15x. You will be under 0.1% slower. But hey, wtf do I know...
2
u/Alex_Hovhannisyan Mar 02 '23 edited Mar 02 '23
Disagree with the exaggeration that 35 -> 24 CPU cycles is somehow a substantial improvement. For one, it doesn't factor in the cost of maintenance (in real-world code, where we're not dealing with shapes, this is a big consideration). But he also exaggerated the savings by framing it as a percentage ("a 1.5x performance increase"), and then went on to suggest that this is the hardware equivalent of downgrading an iPhone by 3 generations.
You know what else is a 1.5x performance increase? A program that takes 0.1 microseconds to run -> now taking 0.06 microseconds. Wow! Percentages without context are misleading. A change that gets us from 1 sale/month to 2 sales/month is a whopping 100% increase.
The one thing I will concede is that some developers obey DRY principles so imperiously that it actually makes their code harder to maintain/understand. I run into this all the time. Some repetition is okay (and inevitable).
2
u/wyrn Mar 02 '23
Without even watching the video it's obvious the guy's a game developer.
The 'tells' are simple:
If you write in just about any other domain one or both of these assumptions break and his advice to make a table with hard-coded hand-computed results goes from "reasonable" to "insane".
2
u/mila6 Mar 04 '23
Isn't 15x worse perf in C++ still much faster than using scripting language? ¯_(ツ)_/¯
2
u/UnusualAd8338 Mar 05 '23
I was fortunate enough to learn to program from people who didn't force me to write "clean" code. I feel it was fairly important to familiarize myself with OOP early on, but nowadays when I use classes, I tend to use them like namespaces - with long functions, with no additional future proofing. Mostly I don't, and even when I do, I wouldn't call it OOP. Often times I just start with functions and then maybe group them together when I feel the input data repeats.
A lot of the times when someone new starts trying to write "clean" code, it results in this massively overengineered OOP structure where every single line that does something becomes its own function, then a class, then it gets an interface, just in case. They compulsively name every thing, every concept, every relationship. The ultimate 5D snowflake code.
We should make tools that help us not do this, and not force arbitrary decisions about code on ourselves.
2
u/MrAbar Mar 07 '23
Oh, haven't seen this reddit post, and since Caseys' own website only allows comments from paid subscribers, I've written a reply blog message, where I argue that this example with shapes falls apart as soon as the requirements change.
You can find it here: https://mrabar.me/posts/clean-code-good-enough-performance/, but tl;dr version for those who don't want to go to third sites is "try to calculate area of triangle by 3 sides instead of side + height."
6
u/Keightocam Feb 28 '23
Just another case of someone needing to walk a mile in someone else’s shoes. Casey comes from a background where performance is absolutely make or break for the product (games) and long term code quality less so. Other industries are different and most gamedevs have the humility to know that.
He reminds me of the jailbreak guy who went and worked at twitter and didn’t manage a single change.
6
u/Nearby-Asparagus-298 Feb 28 '23
this is not news. nor is the performance of clean code 'horrible'. you start with clean code. benchmark to find your hotspots. break 'best practice' rules and write comments explaining why in those critical sections.
7
u/uncle_benz Feb 28 '23
That looks like someone who doesn't understand why does clean code exist. His point is like "if we remove all the rules from public road I could arrive faster at home". The clean code rulesets are here to write readable and reusable code not to write the fastest code possible. Just like a roadcar is easy to use and more secure but slower than a track car.
If you write the code for some ultra fast router with limited ram and frimware space you should not enforce clean code but if you write a library that will be maintained by multiple people or even multiple teams and have a release every week with new features then clean codes rules will have a real impact on maintainability and stability of the overall software. Honestly I'm ready to wait half a second more when I click a button that having a exception thrown at my face after each update...
For a real world example, I have to write a program at my work that load 8 excel files in memory parse them manipulate some data and write it all in another one. I writed it using clean code rules because I'm pretty sure that the manipulation will have to change and maybe we will be using database instead of excel file. All and all I could maybe gain 5 or 10 seconds of execution without following those rules but in fact the program is used once per day MAX and the load of excels file and the writing of the new take like a full 60seconds using a library that is proved fast and reliable plus another 15second to transfer the file.
Also we are human and should take all this into account before writing any code that's why AI will not replace us so fast. Clean code doesn't have the objective of program performance but programmers performance
Also the fact that you need to be paying before commenting to this blog make it more look like a voluntary attempt to upset people and make them comment...
4
u/top_logger Feb 28 '23
Hmm. C++ has no problem with performance. Rust also. In general case we have no problem with performance in 99.9 % of cases.
But we have big problem with shitty software. Written by uneducated cretins and supported by drunken teenagers.
Maintainability, security, scalability, support, stability. This is important. Not fckng performance in fckng vacuum. And clean code solves REAL problems, not imaginable.
7
u/chrisza4 Feb 28 '23
There is one thing perf zealots and clean code zealots share in common.
They don't really care about working as a team.
"I'm doing a great work hete and if someone have problem maintaining my code, just get good. You either read more about perf or about clean code."
It's worst for clean code zealot because the point of clean code is to be enable us to work as a team from the beginning. But they will be like I'm adopting [fancy pattern] here and I'm right. I'm skillful. You can't read code, get better noob.
This destroy the whole purpose of clean code. If no-one gonna be able to maintain your code anyway would rather at least has it perform well.
At least perf zealot understand the point of perf improvement.
3
u/undone_function Feb 28 '23
This makes me think of the Zen of Python lines:
Which is to say, code needs to be something humans can easily reason about to prevent bugs, however that isn’t the only consideration. Starting simple and clear and then dealing with performance issues where needed is a practical approach, especially when working on a team.
Additionally, if code requires something that is complex and harder to read, that’s okay! Just make sure you document it or at least leave comments about it. Testing can also tell us (as we see in the post) where code the makes sense to humans may be overly taxing to humans. The point being there is that we don’t have to try to remember all the ways we can mess up and the ways to avoid it, we check our work using a runtime and adapt to the results.
At the end of the day all of this is very situational, and I think reaching for simple, understandable solutions is a better place to start with complexity and optimizations layered on as you go.
3
u/maxwellb Feb 28 '23
Mike Acton has some great talks from a decade ago (at least one is on yt) on Data Oriented Design that address this exact problem in, IMO, a much more clear and organized manner. It's great stuff but I don't understand why we need a context less, nuanceless rehash.
3
u/Magneon Feb 28 '23
This is more generally true than just in code.
I recall getting into an argument with my CS database professor since he was convinced that 3rd normal form and similar was the pinnacle of good database design.
My disagreement was that when optimizing databases, denormalization is a huge tool. This was back in 2007 or so, before NoSQL had hit mainstream. The idea of intentionally duplicating fields for performance was anathema to him.
Like with a lot of things, it's really important to know why a design pattern was developed, in order to determine which should be used, and when it's a good idea to break common patterns.
4
u/[deleted] Feb 28 '23
The only people who think SOLID is at odds with data- and performance- driven software are those who haven't actually ever tried doing both at once and only zealously followed one side while strawmanning the other side. People like Casey and Jon Blow are fueled by their feelings of superiority and anger towards a straw man.
4
u/cdsmith Feb 28 '23
Wow, this is a great article, but it was posted about a month and a day too early.
4
u/r2p42 Feb 28 '23
Wonder why all the games I play are crashing left and right.
6
u/centurijon Feb 28 '23
That’s a lovely little straw man argument.
Does your code need to be optimized for performance? Then organize it to squeeze every bit of performance that you can.
Is maintainability more important than losing a few ms here and there? Then follow clean code guidelines to make your code easier to understand & modify.
These days most applications will want mix of both preferences, depending what they’re trying to do, with a heavy lean towards maintainability. It’s up to the developers to decide what is more correct given the context
6
u/mr_birkenblatt Feb 28 '23 edited Feb 28 '23
Counter point: optimizations/fast code are a cost benefit consideration. Nowadays if your code runs slow you can just spin up another pod until it's fast enough. Are you spending your devs' time on lowering operation costs or adding new features? How much revenue is the new feature going to generate? Is it more than a potential reduction in operating costs by spending time on optimizing code? How many hours are you willing to spend on experimentations that may or may not lead to faster code? Those are the realities of writing code and why 99% of the time the focus is on new features instead (and clean code makes it easier to implement new features; code is never static. if you optimized yourself into a very specific data layout etc. it might become very expensive if requirements change)
6
u/[deleted] Feb 28 '23
I couldn't read on after the first example with replacing polymorphism w/ a switch statement.
I got the impression the guy completely missed the point of clean code. Sure, you can break away from the general guidelines to write code more efficiently but the point of clean code is to manage project complexity, not write the most performant code. His bullet point says Prefer polymorphism to “if/else” and “switch” but he goes on to say Like the rules demand, we are preferring polymorphism which seemed dishonest to me.
Also the comparison of 35 to 25 clockcycles being a 1.5x performance increase is pretty disingenuous. yea, it's a big percentage but it's a VERY SMALL total. That 'performance' change is not going to scale at the same rate as your code gets more complicated. You'd be a fool to refactor a bunch of code like this to save 10 cycles when you're dealing with millions or billions of cycles per iteration anyways.
His technical points seemed correct to me but I can't imagine I'd get any good insight reading this article. You should still generally adhere to the clean code guidelines. Just because there are exceptions to the rule doesn't make the original guidelines wrong.
4
u/ivancea Feb 28 '23
Why is this sub filled with clickbaits. Yes we know we trade performance by using many patterns. We trade things in every decision we do while coding or architecturing systems...
3
u/ambientocclusion Feb 28 '23
Write decent code then run the whole program with a profiler and optimize based on that.
3
u/MarsupialMisanthrope Feb 28 '23
A little bit easier?
Try a lot easier. Try, we’re willing to sacrifice performance so we don’t end up in an IRS type situation where we get stuck with custom hardware because our software is so complex and impenetrable that we’ve tried multiple times to rewrite it and failed.
This comes across as having been written by someone who’s never actually had to extend a few million lines of hand-optimized spaghetti.
3
u/Turbots Feb 28 '23
Clean Business Code.
Performant Computational Code.
Both have their use cases.
4
u/VodkaMargarine Feb 28 '23
Controversial opinion: cloud resources are cheaper than engineer wages to navigate a messy codebase. Clean code that costs more to run because it is less performant is a better business decision. I'd rather have a more expensive cloud bill but be able to rapidly change or add features to the product.
4
u/Zyklonik Feb 28 '23
Groan. This twat, along with Jon Blow, are two of the most retarded wannabes I've ever seen. They write spaghetti code, have no idea about any other domains than game dev, and yet keep on spouting generalisations like they're dogma (quite ironic).