Skip to content

Commit b167a47

Browse files
committed
FSharp.Core: Map: micro optimizations
Not very visible in benchmarks from PR, need more focused benches. isEmpty branch should be well predicted as false.
1 parent 8c6652e commit b167a47

1 file changed

Lines changed: 8 additions & 9 deletions

File tree

src/fsharp/FSharp.Core/map.fs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -81,16 +81,14 @@ module MapTree =
8181
#endif
8282

8383
let inline height (m: MapTree<'Key, 'Value>) =
84-
if isEmpty m then 0
85-
else
86-
match m with
87-
| :? MapTreeNode<'Key, 'Value> as mn -> mn.Height
88-
| _ -> 1
84+
match m with
85+
| :? MapTreeNode<'Key, 'Value> as mn -> mn.Height
86+
| _ -> 1 - (# "ceq" m null : int #) // 1 branch less
8987

9088
let mk l k v r : MapTree<'Key, 'Value> =
9189
let hl = height l
9290
let hr = height r
93-
let m = max hl hr
91+
let m = if hl > hr then hl else hr
9492
if m = 0 then // m=0 ~ isEmpty l && isEmpty r
9593
MapTree(k,v)
9694
else
@@ -101,8 +99,9 @@ module MapTree =
10199

102100
let rebalance t1 (k: 'Key) (v: 'Value) t2 : MapTree<'Key, 'Value> =
103101
let t1h = height t1
104-
let t2h = height t2
105-
if t2h > t1h + 2 then (* right is heavier than left *)
102+
let t2h = height t2
103+
let hdiff = t1h - t2h
104+
if hdiff < -2 then (* right is heavier than left *)
106105
let t2' = asNode(t2)
107106
(* one of the nodes must have height > height t1 + 1 *)
108107
if height t2'.Left > t1h + 1 then (* balance left: combination *)
@@ -111,7 +110,7 @@ module MapTree =
111110
else (* rotate left *)
112111
mk (mk t1 k v t2'.Left) t2'.Key t2'.Value t2'.Right
113112
else
114-
if t1h > t2h + 2 then (* left is heavier than right *)
113+
if hdiff > 2 then (* left is heavier than right *)
115114
let t1' = asNode(t1)
116115
(* one of the nodes must have height > height t2 + 1 *)
117116
if height t1'.Right > t2h + 1 then

0 commit comments

Comments
 (0)