Smith Dwayne
Smith Dwayne

Reputation: 2807

Reducing Condition statement for Large data

I am doing some sample programs in C++. I have 100,000 single column data in a Text File. I loaded that all data into a std::vector. Now I need to check the first character of every data whether it is '#' or '%' or '$'. The data are in Sorted manner in the way of '#','$','%'. I can do programming for this like Below.

for ( i = 0; i < myArray.size(); i++)
{
  if(mrarray[i][0]=='#')
  {
    // do some process for '#' values
  }
 else if(mrarray[i][0]=='$')
  {
    // do some process for '$' values
  }
 else if(mrarray[i][0]=='%')
  {
    // do some process for '%' values
  }

}

My Question is " Is it a best way to do this ? . Is there any other way to do this program with better efficiency ? " ???

Upvotes: 0

Views: 76

Answers (2)

Jarod42
Jarod42

Reputation: 218098

As state in why-is-processing-a-sorted-array-faster-than-an-unsorted-array, It may be more efficient to sort your lines first (based on first character) and then process your vector.

The switch statement proposed by David would be my choice.

But as alternative, you may try an array of function pointer, something like:

using my_function_pointer = void (*)(const std::string&/*, other required stuff*/);
const my_function_pointer funs[256] = { dummy_f, dummy_f, .., f_charp, f_dollar, f_mod, dummy_f, ..};

for ( i = 0; i < myArray.size(); i++) {
    funs[myArray[i][0]](myArray[i] /*, other required stuff*/);
}

And anyway, you need to benchmark your change as for any optimization.

Upvotes: 1

David
David

Reputation: 4873

That's about as efficient as it gets, the only thing that will make it a bit faster is using a switch statement.

for ( i = 0; i < myArray.size(); i++)
{
  switch(myArray[i][0]){
    case '#':
      // Do stuff
      break;
    case '$':
      // Do stuff
      break;
    case '%':
      // Do stuff
      break;
  }
}

I'm also assuming you're only doing this once. If you're doing it more than once with the same data, then it can be made more efficient by sorting it. If that's the case, let me know and I will update my answer.

Upvotes: 1

Related Questions