Skip to content

Commit

Permalink
Make Box2d::contains and Box2d intersects faster
Browse files Browse the repository at this point in the history
Chaining simple && conditions produces branch instructions in some cases. Replacing the logical and with bitwise & to ensure the compiler does not produce branches makes a big performance difference.
  • Loading branch information
nical committed May 19, 2024
1 parent 6b2aece commit b0a22dd
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions src/box2d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,25 +161,34 @@ where
/// Returns `true` if the two boxes intersect.
#[inline]
pub fn intersects(&self, other: &Self) -> bool {
self.min.x < other.max.x
&& self.max.x > other.min.x
&& self.min.y < other.max.y
&& self.max.y > other.min.y
// Use bitwise and instead of && to avoid emitting branches.
(self.min.x < other.max.x)
& (self.max.x > other.min.x)
& (self.min.y < other.max.y)
& (self.max.y > other.min.y)
}

/// Returns `true` if this box2d contains the point `p`. A point is considered
/// in the box2d if it lies on the left or top edges, but outside if it lies
/// on the right or bottom edges.
#[inline]
pub fn contains(&self, p: Point2D<T, U>) -> bool {
self.min.x <= p.x && p.x < self.max.x && self.min.y <= p.y && p.y < self.max.y
// Use bitwise and instead of && to avoid emitting branches.
(self.min.x <= p.x)
& (p.x < self.max.x)
& (self.min.y <= p.y)
& (p.y < self.max.y)
}

/// Returns `true` if this box contains the point `p`. A point is considered
/// in the box2d if it lies on any edge of the box2d.
#[inline]
pub fn contains_inclusive(&self, p: Point2D<T, U>) -> bool {
self.min.x <= p.x && p.x <= self.max.x && self.min.y <= p.y && p.y <= self.max.y
// Use bitwise and instead of && to avoid emitting branches.
(self.min.x <= p.x)
& (p.x <= self.max.x)
& (self.min.y <= p.y)
& (p.y <= self.max.y)
}

/// Returns `true` if this box contains the interior of the other box. Always
Expand Down

0 comments on commit b0a22dd

Please sign in to comment.