How to evaluate which coding approach is best?

Let's say for example that we have two different ways was can code the exact same program to achieve the same result.

What is the best way to determine which of the two methods is the best solution?

Is it as simple as basing it on how long the program takes to run or is there a more sophisticated way?

Many thanks!

J

It's very hard to give a general answer without knowing what methods are being considered.

"Best for what" is often a good question... As an example, hash tables can be very fast to read best-case, but used badly they can be no better than a linear search. They're also space-inefficient, strewing information thinly by design... You wouldn't want to use them to store huge amounts of data. Trees are slower to read than a hash table's best, but a balanced tree's worst case time is smaller than a poorly hashed table -- but adding to or changing a tree can be complicated and slow since it may need balancing. Not all data is really suitable for either anyway...

So, more information's needed.

I'll say whay has already been said another way - alogrithm choice affects resources in a really bad way when you pick the wrong method for the job. Resources = time, memory, i/o.

  1. what resource limits do you want to enforce
  2. what is your data like

Thanks for the feedback ..

In this specific case I am considering whether to run a simple function or or leave the equation in the loop.

What I'll do is increase the instances substantially to see what happens.

There's probably value to inlining a simple equation like that. You could make it an inline function though, and get the benefits of inlining while still encapsulating it. Sort of like a macro, but with the same side-effects as a normal function call.

inline int square(int a)
{
         return(a*a);
}