Using tables to optimize your code for speed (C/C++).

Often you can obtain a great improvement of performances simply using tables instead of algorithms. For example, if you need to compute factorials you can use three different approaches, a recursive function (which is the natural solution for the factorial problem), an iterative function or you can compute the factorial and then you can use the computed values each time they are needed.

long long tableFact(int a)



    long long result[12] =


        1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600


    return (result[a]);



The above code stores in the result array the values for the factorial of the first 12 numbers. The performance improvement is clear, beacause for each call there is only an assignment without any computation.

The following chart shows the performances for the three algorithms considered.

table performances

Naturally the use of tables can increase the memory requirement for the software, so you should take care of this problem.


You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *