title: GCD Poor Performance
body: <p>As you may remember, I am trying to use GCD to speed up some of my code, namely a collision detection and resolution engine.  However, I am clearly doing something wrong because all of my GCD code is significantly slower and less consistent than my serial code (between 1.4x and 10x slower).  Allow me to give you an example: I am iterating over an array in a bubble-sort fashion to determine all possible collisions among objects in that array:</p>
  
  <pre><code>- (double) detectCollisionsInArray:(NSArray*)objects
  {   
      int count = [objects count];
      if (count &gt; 0)
      {       
          double time = CFAbsoluteTimeGetCurrent();
          for (int i = 0; i &lt; count; i++)
          {
              for (int j = i + 1; j &lt; count; j++)
              {
                  /** LOTS AND LOTS OF WORK FOR EACH OBJECT **/
              }
          }
  
          return CFAbsoluteTimeGetCurrent() - time;
      }
  
      return 0;
  }
  </code></pre>
  
  <p>Pretty straightforward, and it seems to perform well given the constraints of the problem.  However, I would like to take advantage of the fact that the state of each object is not modified in the code section and use GCD to parallelize this work.  To do this I am trying something like this:</p>
  
  <pre><code>- (double) detectCollisionsInArray:(NSArray*)objects
  {   
      int count = [objects count];
      if (count &gt; 0)
      {
          NSOperationQueue* opQueue = [[NSOperationQueue alloc] init];
          NSBlockOperation* blockOperation = nil;
  
          double time = CFAbsoluteTimeGetCurrent();
          for (int i = 0; i &lt; count; i++)
          {
              for (int j = i + 1; j &lt; count; j++)
              {
                  void (^workBlock) (void) = ^() 
                  {
                      /** LOTS AND LOTS OF WORK FOR EACH OBJECT **/
                  };
  
                  if (!blockOperation)
                  {
                      blockOperation = [NSBlockOperation blockOperationWithBlock:b];
                  }
                  else
                  {
                      [blockOperation addExecutionBlock:workBlock];
                  }
              }
          }
  
          [opQueue addOperation:blockOperation];
          [opQueue autorelease];
  
          return CFAbsoluteTimeGetCurrent() - time;
      }
  
      return 0;
  }
  </code></pre>
  
  <p>Can anyone help to put me on the right track and perhaps provide a link to a good GCD tutorial?  I have looked over several GCD tutorials and scoured all of the documentation and I still feel that my grasp on the subject is tenuous at best.  Thanks!</p>