r/AskComputerScience 13d ago

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

1

u/Leverkaas2516 13d ago

It often does carry some execution-time overhead like this, yes. The idea is this: most of your code does not need to be optimized for speed. If you optimize while writing it, you're wasting resources and making the code hard to work with.

Once you figure out where speed matters, if the code is clean, then it's a lot easier to understand how to change the parts that need to be optimized. You end up with clean, optimized code and finish the development work faster.

If you try to optimize up front, you take longer to finish and end up with 20k lines of code that has hidden flaws and most of the team is scared to touch. (I just did a code review on a change to such a module yesterday.)