From 86b876f5f020ed7aeaa7aa0a552dfb9ac2f75a26 Mon Sep 17 00:00:00 2001 From: Andrei Borzenkov Date: Tue, 15 Oct 2024 16:50:06 +0400 Subject: [PATCH] Move leaf branch to the end of switch expression, as the most unlikely This PR didn't touch folds and map as benchmark showed us that it performs worse. --- src/PersistentOrderedMap.mo | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/PersistentOrderedMap.mo b/src/PersistentOrderedMap.mo index 62f55b7a..d13e7efd 100644 --- a/src/PersistentOrderedMap.mo +++ b/src/PersistentOrderedMap.mo @@ -501,13 +501,13 @@ module { /// where `n` denotes the number of key-value entries stored in the tree. public func size(t : Map) : Nat { switch t { - case (#leaf) { 0 }; case (#red(l, _, r)) { size(l) + size(r) + 1 }; case (#black(l, _, r)) { size(l) + size(r) + 1 - } + }; + case (#leaf) { 0 } } }; @@ -633,7 +633,6 @@ module { public func get(t : Map, compare : (K, K) -> O.Order, x : K) : ?V { switch t { - case (#leaf) { null }; case (#red(l, xy, r)) { switch (compare(x, xy.0)) { case (#less) { get(l, compare, x) }; @@ -647,7 +646,8 @@ module { case (#equal) { ?xy.1 }; case (#greater) { get(r, compare, x) } } - } + }; + case (#leaf) { null } } }; @@ -714,9 +714,6 @@ module { : Map{ func ins(tree : Map) : Map { switch tree { - case (#leaf) { - #red(#leaf, (key,val), #leaf) - }; case (#black(left, xy, right)) { switch (compare (key, xy.0)) { case (#less) { @@ -744,6 +741,9 @@ module { #red(left, (key,newVal), right) } } + }; + case (#leaf) { + #red(#leaf, (key,val), #leaf) } }; }; @@ -903,14 +903,14 @@ module { }; func del(tree : Map) : Map { switch tree { - case (#leaf) { - tree - }; case (#red(left, xy, right)) { delNode(left, xy, right) }; case (#black(left, xy, right)) { delNode(left, xy, right) + }; + case (#leaf) { + tree } }; };