Skip to content

Commit 8cbc564

Browse files
committed
Somewhat optimize the generic Features::requires_unknown_bits
It turns out we spend several percent of our routefinding time just checking if nodes and channels require unknown features byte-by-byte. While the cost is almost certainly dominated by the memory read latency, avoiding doing the checks byte-by-byte should reduce the branch count slightly, which may reduce the overhead.
1 parent 7f4b466 commit 8cbc564

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

lightning/src/ln/features.rs

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -801,15 +801,23 @@ impl<T: sealed::Context> Features<T> {
801801
pub fn requires_unknown_bits(&self) -> bool {
802802
// Bitwise AND-ing with all even bits set except for known features will select required
803803
// unknown features.
804-
let byte_count = T::KNOWN_FEATURE_MASK.len();
805-
self.flags.iter().enumerate().any(|(i, &byte)| {
806-
let unknown_features = if i < byte_count {
807-
!T::KNOWN_FEATURE_MASK[i]
808-
} else {
809-
0b11_11_11_11
810-
};
811-
(byte & (ANY_REQUIRED_FEATURES_MASK & unknown_features)) != 0
812-
})
804+
let mut known_chunks = T::KNOWN_FEATURE_MASK.chunks(8);
805+
for chunk in self.flags.chunks(8) {
806+
let mut flag_bytes = [0; 8];
807+
flag_bytes[..chunk.len()].copy_from_slice(&chunk);
808+
let flag_int = u64::from_le_bytes(flag_bytes);
809+
810+
let known_chunk = known_chunks.next().unwrap_or(&[0; 0]);
811+
let mut known_bytes = [0; 8];
812+
known_bytes[..known_chunk.len()].copy_from_slice(&known_chunk);
813+
let known_int = u64::from_le_bytes(known_bytes);
814+
815+
const REQ_MASK: u64 = u64::from_le_bytes([ANY_REQUIRED_FEATURES_MASK; 8]);
816+
if flag_int & (REQ_MASK & !known_int) != 0 {
817+
return true;
818+
}
819+
}
820+
false
813821
}
814822

815823
pub(crate) fn supports_unknown_bits(&self) -> bool {

0 commit comments

Comments
 (0)