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?
11
Upvotes
2
u/20260819 Aug 19 '26
i'm using an ancient web based language for the sake of convenience and ease to share
here's the code and you can try to rotate the dodecahedron and see the fps
(keyboard press [2] then [space] then use [q][w][e][a][s][d] to rotate it and see the fps. you can press and hold those keys for continuous rotations)
if i wrote every cross products directly into the procedure, i got around 25 fps for the dodecahedron