[英]C# - Fastest way to convert an int and put it in a byte array with an offset
我正在編寫自定義字節流,並且我最希望以最快的方式工作的寫/讀方法。 這是我目前對int32的write和read方法的實現:
public void write(int value)
{
unchecked
{
bytes[index++] = (byte)(value);
bytes[index++] = (byte)(value >> 8);
bytes[index++] = (byte)(value >> 16);
bytes[index++] = (byte)(value >> 24);
}
}
public int readInt()
{
unchecked
{
return bytes[index++] |
(bytes[index++] << 8) |
(bytes[index++] << 16) |
(bytes[index++] << 24);
}
}
但是我真正想要做的是將“ int
”轉換為字節指針(或類似的指針),然后將內存復制到具有給定“ index
”作為offset
的“ bytes
”數組中。 在C#
甚至可能嗎?
目標是:
避免創建新的數組。
避免循環。
避免多次分配“ index
”變量。
減少指令數量。
您的代碼非常快,但是您可以通過以下更改來提高速度(幾乎快2倍):
bytes[index] = (byte)(value);
bytes[index+1] = (byte)(value >> 8);
bytes[index+2] = (byte)(value >> 16);
bytes[index+3] = (byte)(value >> 24);
index = index + 4;
unsafe
{
fixed (byte* pbytes = &bytes[index])
{
*(int*)pbytes = value;
value = *(int*)pbytes;
}
}
但是要小心可能發生的數組索引溢出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.