Is a std::vector lookup faster than performing a simple operation?
<p>I'm trying to optimize some C++ code for speed, and not concerned about memory usage. If I have some function that, for example, tells me if a character is a letter:</p>

<pre><code>bool letterQ ( char letter ) {
    return (lchar&gt;=65 &amp;&amp; lchar&lt;=90) ||
       (lchar&gt;=97 &amp;&amp; lchar&lt;=122);
}
</code></pre>

<p>Would it be faster to just create a lookup table, i.e.</p>

<pre><code>int lookupTable[128];
for (i = 0 ; i &lt; 128 ; i++) {
    lookupTable[i] = // some int value that tells what it is
}
</code></pre>

<p>and then modifying the letterQ function above to be</p>

<pre><code>bool letterQ ( char letter ) {
    return lookupTable[letter]==LETTER_VALUE;
}
</code></pre>

<p>I'm trying to optimize for speed in this simple region, because these functions are called a lot, so even a small increase in speed would accumulate into long-term gain.</p>

<p>EDIT: </p>

<p>I did some testing, and it seems like a lookup array performs significantly better than a lookup function if the lookup array is cached. I tested this by trying</p>

<pre><code>for (int i = 0 ; i &lt; size ; i++) {
      if ( lookupfunction( text[i] ) )
      // do something
}
</code></pre>

<p>against</p>

<pre><code>bool lookuptable[128];
for (int i = 0 ; i &lt; 128 ; i++) {
    lookuptable[i] = lookupfunction( (char)i );
}

for (int i = 0 ; i &lt; size ; i++) {
    if (lookuptable[(int)text[i]])
        // do something
}
</code></pre>

<p>Turns out that the second one is considerably faster - about a 3:1 speedup.</p>
