From 176505b897edea2dd0e7ad49349defdebae55ca1 Mon Sep 17 00:00:00 2001 From: Simon Gardling Date: Tue, 18 Feb 2025 20:13:19 -0500 Subject: [PATCH] MAJOR (25%+) perf increase with propegate iterator and copies --- src/board.rs | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/board.rs b/src/board.rs index be64167..9e42443 100644 --- a/src/board.rs +++ b/src/board.rs @@ -166,7 +166,7 @@ impl Board { } /// Get a reference to a backing [`BitBoard`] - pub const fn board(&self, color: Piece) -> &BitBoard { + const fn board(&self, color: Piece) -> &BitBoard { match color { Piece::Black => &self.black_board, Piece::White => &self.white_board, @@ -174,7 +174,7 @@ impl Board { } /// Get a mutable reference to a backing [`BitBoard`] - pub const fn board_mut(&mut self, color: Piece) -> &mut BitBoard { + const fn board_mut(&mut self, color: Piece) -> &mut BitBoard { match color { Piece::Black => &mut self.black_board, Piece::White => &mut self.white_board, @@ -249,13 +249,19 @@ impl Board { return 0; }; - let pos_s: Vec<(usize, usize)> = self.propegate_from_dry(i, j, starting_color).collect(); - let pos_len = pos_s.len(); - for (i, j) in pos_s { + // PERF! avoid clones and collections here using raw pointers + let iterator = unsafe { + // SAFETY! `propegate_from_dry` should not have overlapping chains + // if overlapping chains were to exist, `self.place_unchecked` could collide with `self.get` + (&*(self as *const Self)).propegate_from_dry(i, j, starting_color) + }; + let mut count = 0; + for &(i, j) in iterator { self.place_unchecked(i, j, starting_color); + count += 1; } - pos_len + count } /// Propegate piece captures originating from (i, j) @@ -266,7 +272,7 @@ impl Board { i: usize, j: usize, starting_color: Piece, - ) -> impl Iterator + use<'_> { + ) -> impl Iterator + use<'_> { ADJ_LOOKUP[i][j] .iter() .filter_map(move |chain| { @@ -281,7 +287,6 @@ impl Board { end_idx.and_then(|idx| chain.get(..idx)) }) .flatten() - .cloned() } /// Count the number of a type of [`Piece`] on the board