From aafee600333fe6f855f4a881a0d8992ea08cf144 Mon Sep 17 00:00:00 2001 From: Chocobo1 Date: Wed, 26 Jan 2022 12:20:21 +0800 Subject: [PATCH] Allocate memory on stack whenever feasible The fast path gives another 20% speed up than the slower path. --- src/base/bittorrent/ltqbitarray.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/base/bittorrent/ltqbitarray.cpp b/src/base/bittorrent/ltqbitarray.cpp index b965da70c..83b62a8d0 100644 --- a/src/base/bittorrent/ltqbitarray.cpp +++ b/src/base/bittorrent/ltqbitarray.cpp @@ -47,9 +47,22 @@ namespace BitTorrent::LT { QBitArray toQBitArray(const lt::bitfield &bits) { + const int STACK_ALLOC_SIZE = 10 * 1024; + const char *bitsData = bits.data(); const int dataLength = (bits.size() + 7) / 8; + if (dataLength <= STACK_ALLOC_SIZE) + { + // fast path for small bitfields + char tmp[STACK_ALLOC_SIZE]; // uninitialized for faster allocation + for (int i = 0; i < dataLength; ++i) + tmp[i] = reverseByte(bitsData[i]); + + return QBitArray::fromBits(tmp, bits.size()); + } + + // slow path for big bitfields auto tmp = std::make_unique(dataLength); for (int i = 0; i < dataLength; ++i) tmp[i] = reverseByte(bitsData[i]);