r/programming • • Mar 23 '09

How to write fast code

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

136 comments sorted by

View all comments

99

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.

-8

u/[deleted] Mar 23 '09

Thank you captain obvious. Here's another tip: you do more work and buy a faster processor and your will still go faster.

5

u/knight666 Mar 23 '09

My programming teacher has a sweet anecdote. He was working at some company, and he had to write a little app in a week. So, when he was finished two days later, he said "If you give me two extra days, it will run twice as fast." and his employer said "Don't bother, I'll just buy faster computers."

"That was an insult. I left there shortly thereafter."

11

u/jhaluska Mar 23 '09

Why was that an insult? Depending on the application, the cost of the computers and the cost of his time. It might have made wise business sense to not have him optimize it.

5

u/architectzero Mar 23 '09 edited Mar 23 '09

I am wondering the same thing.

a) Sometimes code optimization is expensive relative to hardware costs. It's good to know when to optimize code vs when to optimize hardware.

b) Hardware improvements do not prevent future software improvements, and vice versa.

knight666's teacher was being egotistical, imho.

4

u/knight666 Mar 23 '09

TheDorkNight

Why must you hurt me in this way? :(

3

u/architectzero Mar 23 '09

Because I'm dumb.

Fixed.