title: Why is sending data with BinaryWriter so much faster using Write(Byte[]) instead of using foreach and Write(Byte)?
body: <p>I'm using <code>C#</code> and <code>32feet</code> (version 3.5) to send blocks of 250 bytes over bluetooth (SPP) to an embedded device I'm currently writing firmware for.</p>
  
  <p>I'm setting up my connection with the following code:</p>
  
  <pre><code>var client = new BluetoothClient();
  client.Encrypt = true;
  client.Connect(bluetoothAddress, ServiceClassId);
  NetworkStream stream = client.GetStream();
  var writer = new BinaryWriter(stream);
  </code></pre>
  
  <p>I got some problem with very low throughput and each block took about 100 ms to be transferred with the following code:</p>
  
  <pre><code>public void SendData(List&lt;byte&gt; data)
  {
      try
      {
          foreach (byte d in data)
          {
              writer.Write(d);
          }
          writer.Flush();
      }
      catch (Exception)
      {
          // The connection was lost
          ConnectionCleanup();
      }
  }
  </code></pre>
  
  <p>After changing the code block above to the code below each block is transmitted within 4 ms.</p>
  
  <pre><code>try
  {
      writer.Write(data.ToArray());
      writer.Flush();
  }
  catch (Exception)
  {
      // The connection was lost
      ConnectionCleanup();
  }
  </code></pre>
  
  <p>I'm struggling to understand how this "simple" code change can have such large impact on the throughput. Can anyone help me explain what's going on? I guess it has something to do with the underlying mechanism of 32feet?</p>
  
  <p>I've changed the code back and forth and the result is the same every time. The transmitted data is also the same.</p>
  
  <p>I've also connected to the device directly from Windows and then opened the COM-port in Realterm to send the same data. In this case I get similar throughput as using <code>writer.Write(data.ToArray())</code>.</p>
  
  <p>I'm using the <code>Microsoft Bluetooth Stack</code>.</p>