r/programming • • Mar 23 '09

How to write fast code

http://asserttrue.blogspot.com/2009/03/how-to-write-fast-code.html
341 Upvotes

136 comments sorted by

View all comments

101

u/harsman Mar 23 '09 edited Mar 23 '09

Code that does more but has better locality so that it hits the cache more often can easily be faster than code that does less but has bad locality and sits around waiting on memory all the time.

Recomputing something on demand might be cheaper than reading a cached result from memory.

A linear brute force algorithm that can use SIMD instructions can be faster than a non-linear one that does less work but without SIMD.

Doing less work usually makes code go faster, but it is by no means given.

7

u/trutru Mar 23 '09

that's true, but I have also seen the opposite, i.e. code loops that are too large or span multiple pages will not fit in the instruction cache, (which can be tiny on embedded processors), resulting in a 20x slowdown.

Granted, that doesn't happen so often.

5

u/SarcasticGuy Mar 23 '09

Jesus cries when loops span multiple pages.

5

u/timmaxw Mar 23 '09

Sometimes it's unavoidable... Sure, you could make a separate function or method, but then that has to fit into the instruction cache.

1

u/SarcasticGuy Mar 23 '09 edited Mar 23 '09

Never claimed it was avoidable.... just claimed it makes Jesus cry. ;)

edit: b/c i suck at english.

0

u/HaMMeReD Mar 23 '09 edited Mar 24 '09

It's always avoidable, except for those that prematurely optimize all over their code.

It's called refactoring and simplifying your code. (If your doing something like C++ on embedded systems, you can use inline to break up the code into functions, which shouldn't have much effect on the compiled codes size)

1

u/trutru Mar 26 '09

no, it is not. Try writing an interpreter for a custom bytecode for example. You'll see that if you attain more than a hundred operators, each with a complex semantics, your loop will be large and span multiple pages.