簡體   English   中英

為什么使用Write(Byte [])而不是使用foreach和Write(Byte),使用BinaryWriter發送數據的速度要快得多?

[英]Why is sending data with BinaryWriter so much faster using Write(Byte[]) instead of using foreach and Write(Byte)?

我正在使用C#32feet (版本3.5)通過藍牙(SPP)將250字節的塊發送到我正在為其編寫固件的嵌入式設備。

我正在使用以下代碼設置我的連接:

var client = new BluetoothClient();
client.Encrypt = true;
client.Connect(bluetoothAddress, ServiceClassId);
NetworkStream stream = client.GetStream();
var writer = new BinaryWriter(stream);

我在吞吐量非常低的情況下遇到了一些問題,每個塊需要大約100毫秒才能使用以下代碼進行傳輸:

public void SendData(List<byte> data)
{
    try
    {
        foreach (byte d in data)
        {
            writer.Write(d);
        }
        writer.Flush();
    }
    catch (Exception)
    {
        // The connection was lost
        ConnectionCleanup();
    }
}

將上面的代碼塊更改為下面的代碼后,每個塊在4 ms內發送。

try
{
    writer.Write(data.ToArray());
    writer.Flush();
}
catch (Exception)
{
    // The connection was lost
    ConnectionCleanup();
}

我很難理解這種“簡單”的代碼更改如何對吞吐量產生如此大的影響。 誰能幫我解釋一下發生了什么? 我想這與32feet的底層機制有關?

我來回改變了代碼,結果每次都是一樣的。 傳輸的數據也是一樣的。

我還直接從Windows連接到設備,然后在Realterm中打開COM端口以發送相同的數據。 在這種情況下,我獲得與使用writer.Write(data.ToArray())類似的吞吐量。

我正在使用Microsoft Bluetooth Stack

看一下BinaryWriter參考源Write(byte)調用底層流的WriteByte(byte) ,而Write(byte[])調用Write(byte[], int, int) 進一步看,我們看到NetworkStream沒有覆蓋虛方法WriteByte,因此使用了基本實現

// Writes one byte from the stream by calling Write(byte[], int, int).
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any 
// subclass that maintains an internal buffer.  Then, it can help perf
// significantly for people who are writing one byte at a time.
public virtual void WriteByte(byte value)
{
    byte[] oneByteArray = new byte[1];
    oneByteArray[0] = value;
    Write(oneByteArray, 0, 1);
}

此外, NetworkStream沒有內部緩沖區,它只是將Write調用傳遞給底層Socket 您在第一種情況下進行250次網絡呼叫,在第二種情況下進行1次,因此性能差異的原因應該是顯而易見的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM