r/AskComputerScience • u/20260819 • Aug 19 '26
is clean code usually not fast?
to be specific i'm writing a cpu-based rasterizer. the maths are not difficult but i find a strange property: if i divide the procedure into some small functions, the code looks cleaner and is easier to maintain but a bit slower. on the contrary if i put everything into a single procedure, it looks stupid but fast. why is that? an example illustrating this
code 1:
if cross_product(x0,y0,x1,y1)>0 then zzz
(and i write a "cross_product" function separately)
code 2:
c=x0y1-y0x1
if c>0 then zzz
code 3:
if x0y1-y0x1>0 then zzz
if i write the entire algorithm in the style of "code 3", it runs the fastest. "code 1" is slowest
is it normal?
View all comments
1
u/ka-splam Aug 23 '26 edited Aug 23 '26
I think this is an unresolved tension in programming, driven by several valid ideas clashing, and people thinking about different contexts:
Casey Muratori argues that the industry has gone too far towards 'clean code' abstractions, and has video rants on the topic: "Clean code, horrible performance" and Twitter and Visual Studio Rant where he demonstrates that the visual studio debugger of old was more responsive on 20 year old hardware than the current one is today on modern hardware, and the visual studio team have a feedback option "opening an empty workspace should take X seconds" which has no choice below 10 seconds.
As I said I don't think this tension has any resolution. You could ask yourself if
is helping in any way that a comment
isn't. And sometimes you will say "yes it helps me refactor the cross product without missing one place, it helps my tooling and editor autocomplete, it helps avoid code and comments getting out of sync" and sometimes you will say "splitting it out into a separate function is decorative make-work that feels productive but takes time and doesn't gain anything I care about while slowing my code down".
But if your wider system design has every display call going over a network link then the difference in cross product performance might not matter at all. But if your LLM is zillions of linear algebra calculations and every nanosecond counts, then you'll want to spend more effort than removing the function and inlining the calculation in BASIC. Everything is a design tradeoff 🤷♂️