Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed of memory read vs. simple arithmetic and conditionals

I'm writing a program that requires massive number crunching in any case.

Often, I have the option of either calculating a value by means of {3-4 additions or multiplications and an if-else check or two, maybe a sort of about five numbers}, or reading the value up from a lookup table. Everything is int.

How fast is a memory read in comparsion to such simple operations, roughly?

like image 227
Matt Damon Avatar asked Nov 26 '25 06:11

Matt Damon


2 Answers

Basic principle of performance tuning ; "Don't guess, measure it"

like image 200
Erdinç Taşkın Avatar answered Nov 27 '25 18:11

Erdinç Taşkın


This is impossible to answer in any meaningful way. It depends on the actual code, and on the platform you are using. As a general rule, if there are simple local optimizations that might work, the JIT compiler will do them for you.

You are better doing the following:

  1. Write the program in a simple and natural way.
  2. Get it working.
  3. Run it on a typical input dataset / problem. If it is fast enough, then stop.
  4. Profile the code as it executes a typical input dataset / problem.
  5. Use the profiling results to identify the most critical hotspot in your code.
  6. Examine the code, and identify a possible optimization.
  7. Code the optimization and rerun the profiling. Did it improve things?
  8. Repeat from step 3 until either the program is running fast enough, or you have run out of possible optimizations.

The problem with lookup tables is that you are trading off time for space, and the space usage depends on the number of combinations of inputs that are your application uses. The lookup table approach only pays off in limitted cases.

like image 33
Stephen C Avatar answered Nov 27 '25 18:11

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!