Skip to content

Commit 56b7814

Browse files
authored
Use function rather than closure for heaps to avoid unnecessary heap allocation (TheAlgorithms#148)
1 parent 7ecac6f commit 56b7814

File tree

1 file changed

+5
-7
lines changed

1 file changed

+5
-7
lines changed

src/data_structures/heap.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,14 @@ where
1010
{
1111
count: usize,
1212
items: Vec<T>,
13-
comparator: Box<dyn Fn(&T, &T) -> bool>,
13+
comparator: fn(&T, &T) -> bool,
1414
}
1515

1616
impl<T> Heap<T>
1717
where
1818
T: Default,
1919
{
20-
pub fn new(comparator: Box<dyn Fn(&T, &T) -> bool>) -> Self {
20+
pub fn new(comparator: fn(&T, &T) -> bool) -> Self {
2121
Self {
2222
count: 0,
2323
// Add a default in the first spot to offset indexes
@@ -113,8 +113,7 @@ impl MinHeap {
113113
where
114114
T: Default + Ord,
115115
{
116-
let comparator = |a: &T, b: &T| a < b;
117-
Heap::new(Box::new(comparator))
116+
Heap::new(|a, b| a < b)
118117
}
119118
}
120119

@@ -125,8 +124,7 @@ impl MaxHeap {
125124
where
126125
T: Default + Ord,
127126
{
128-
let comparator = |a: &T, b: &T| a > b;
129-
Heap::new(Box::new(comparator))
127+
Heap::new(|a, b| a > b)
130128
}
131129
}
132130

@@ -173,7 +171,7 @@ mod tests {
173171

174172
#[test]
175173
fn test_key_heap() {
176-
let mut heap: Heap<Point> = Heap::new(Box::new(|a, b| a.0 < b.0));
174+
let mut heap: Heap<Point> = Heap::new(|a, b| a.0 < b.0);
177175
heap.add(Point(1, 5));
178176
heap.add(Point(3, 10));
179177
heap.add(Point(-2, 4));

0 commit comments

Comments
 (0)