2

I am writing a small simulation program where I have a void move(int n) function and a void move() function. As their names suggest, move(int n) makes n moves at a time whereas move() only makes one move.

Now I have two ways of implementing them on mind. Approach 1 is:

public void move()
{
  // make one move
}

public void move(int n)
{
  for (int i=0;i<n;i++)
  {
    move();
  }
}

And approach 2:

public void move(int n)
{
  for (int i=0;i<n;i++)
  {
    // make one move
  }
}

public void move()
{
  move(1);
}

Apparently when the number of moves is large, approach 2 gives time efficiency advantage as we do not make a separate functional call every time we make a move. However, since now the implementation of each move is implemented in a for loop, changing the implementation later on (e.g. fetching metadata or analytical data from each move) seems not to have good modularity. And in cases of making multiple single moves one at a time, approach 2 requires extra function call and extra loop setup.

Assume we do not know about particular future use cases, how should I decide which approach to take?

OneZero
  • 11,556
  • 15
  • 55
  • 92
  • This looks like a micro-optimization scenario. Do you have any supporting results that show that one approach is slower than the other? – Chetan Kinger Apr 28 '15 at 10:29

3 Answers3

1

Realistically, a good JVM should make them pretty equivalent (with inlining mostly, see this answer); you should instead focus on readable code, which definitely makes the first one preferable. If it really matters, I would suggest trying to profile your code with random use cases (e.g. all single moves, all large number of moves, mixed); you'll probably have to make some qualitative decisions about which you view as most likely, and keep in mind it will be implementation dependent if you're writing code likely to be ported.

Community
  • 1
  • 1
sabreitweiser
  • 643
  • 3
  • 13
1

Maybe I'm missing something, but it looks like you only need one function

public void move(int n)
{
  for (int i=0;i<n;i++)
  {
    // make one move
  }
}

For the case when you only need to make one move the extra time it takes to initialize the variable i and make one more comparison is negligible.

0

I would suggest you to use only one function while making moves, be it one move or multiple moves. You should use first approach and keep the void move() private and let void move(int n) call this function which is public.

Paramvir Singh Karwal
  • 597
  • 1
  • 10
  • 24