title: math expression evaluation - very fast - with objective-c
body: <p>i want to evaluate a math expression like y = 2(x * x) + 2.</p>
  
  <p>But i need it in a loop, where the x changes maybe 100000 times.</p>
  
  <p>I have written code to translate the expression in a parse tree.</p>
  
  <p>Then i have a method to evaluate the parse tree.</p>
  
  <pre><code>- (double) evaluate:(TreeNode *)node variable:(double)x
  {
      if ([node _operand] != 0) 
      {
          return [node _operand];
      }
  
      else if ([node _variable] != NULL) 
      {
          return x;
      }
  
      else if ([node _operator] != NULL) 
      {
          if ([[node _operator] isEqualToString: @"+"]) 
          {
              return ([self evaluate:[node left] variable:x] + [self evaluate:[node right] variable:x]);
          }
          else if ([[node _operator] isEqualToString: @"-"]) 
          {
              return ([self evaluate:[node left] variable:x] - [self evaluate:[node right] variable:x]);
          }
          else if ([[node _operator] isEqualToString: @"*"]) 
          {
              return ([self evaluate:[node left] variable:x] * [self evaluate:[node right] variable:x]);
          }
          else if ([[node _operator] isEqualToString: @"/"]) 
          {
              return ([self evaluate:[node left] variable:x] / [self evaluate:[node right] variable:x]);
          }
      }
  
      return 0;
  }
  </code></pre>
  
  <p>Someone said: if i gotta go for speed, i could translate the expression into C code, compile and link it into a dll on-the-fly and load it (takes about a second). That, plus memoized versions of the math functions, could give me the best performance.</p>
  
  <p>How can i achive that ?
  How can i compile the math expression into C code and compile and link it into a dll or so. And then load it on the fly to speed the loop up ?</p>
  
  <p>Thanks a lot !</p>
  
  <p>Chris</p>