r/AskComputerScience • • 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?

10 Upvotes

19 comments sorted by

View all comments

Show parent comment

1

u/20260819 Aug 20 '26

it suits my purposes. i write programs mainly for leisure and studying. it's the learning journey that's important. the final products themselves are not that important...:) most of the time my programs are useless or having tons of available alternatives freely online which can be downloaded straightaway

1

u/ImpressiveOven5867 Aug 20 '26

Well, to each their own I suppose. I appreciate you introducing me to something completely new, and it was interesting figuring out how the compiler worked to make the slower result you were seeing.

1

u/20260819 Aug 20 '26

the difference was noticeable. i did a experiment. for comparison, i rotated the same object (the regular dodecahedron) and recorded the fps. the fps varied and i picked the average values

if everything was calculated by functions: ~16 fps

then i copied the barycentric function into the procedure: ~14 fps

then i replaced one of the cross products with direct calculation: ~16 fps

replaced 2 lines: ~19 fps

3 lines: ~20 fps

all direct calculations, no function: ~25 fps