0

Consider the following Java code:

public void DoStuff(String[] strings, boolean preEval)
{
    final String compareTo = "A Somewhat Long String of Characters";

    for ( int i = 0; i < strings.length; ++i )
    {
         if ( preEval )
         {
              if( strings[i].equals(compareTo) )
              {
                  //do something process intensive
              }
         }

         //do something process intensive
    }

}

Now pay attention to if (preEval) and the inner statement within that. If the algorithm in use requires a condition such as preEval, does it make sense to include the preEval condition for the purposes of code optimization?

From my understanding, evaluating to see if a conditional flag resolves to true or false is much faster than iterating through a collection of characters and comparing each character within that collection with another corresponding character from a different collection.

My knowledge of assembly is about 30% I'd say in terms of the internals and opcodes/mnemonics involved, hence why I'm asking this question.

Update

Note: the code posted here is meant to be language independent; I simply chose Java just for the sake of something tangible and easy to read, as well as something which is widely known among the programmer community.

zeboidlund
  • 9,731
  • 31
  • 118
  • 180

2 Answers2

1

I would say that this would probably be an optimization in most cases.

That said, you should not spend time on optimizing code that has not been measured.

This might for example not be a worthwhile optimization if:

  • most of your cases involves few strings or very short strings.
  • it takes a long time to calculate the preEval parameter before calling the function.

Measure your code under realistic circumstances, identify your bottle necks, then you optimize.

Jens Agby
  • 410
  • 2
  • 9
0

A less costly approach might be to use a HashSet::contains(string) method to check for existence of a string in a collection. You can probably design away the need for string compares while iterating using a HashSet of strings or a HashMap keyed by String.

I always try to use a HashMap where i can to avoid conditional logic entirely.

_ryan

ryan0
  • 1,482
  • 16
  • 21
  • I should have probably clarified I am not encountering this problem in Java or any other language, it was just something I was very curious about - something that I believe is likely to be a language independent feature, however more so CPU dependent. – zeboidlund Aug 22 '12 at 21:39