Skip to content

Commit 0c4ec36

Browse files
committed
Use a faster median calculator for the range map's binary search.
It was inspired from .NET 5's span binary search and performs one less operation. Perform array indexing only once in RangeMap.TryFind. And designtime Farkles with metadata are now called designtime Farkle wrappers.
1 parent 3189187 commit 0c4ec36

File tree

2 files changed

+5
-4
lines changed

2 files changed

+5
-4
lines changed

Diff for: src/Farkle/Builder/DesigntimeFarkle.fs

+1-1
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ type internal DesigntimeFarkleWrapper<'T> = {
173173
with
174174
static member Create (df: DesigntimeFarkle<'T>) =
175175
match df with
176-
| :? DesigntimeFarkleWrapper<'T> as dfwm -> dfwm
176+
| :? DesigntimeFarkleWrapper<'T> as dfw -> dfw
177177
| _ -> {InnerDesigntimeFarkle = df; Name = df.Name; Metadata = GrammarMetadata.Default}
178178
interface DesigntimeFarkle with
179179
member x.Name = x.Name

Diff for: src/Farkle/Collections/RangeMap.fs

+4-3
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ type RangeMap<'key,'a when 'key :> IComparable<'key>> private(arr: RangeMapEleme
5151
// Adapted from .NET's binary search function.
5252
let rec binarySearch lo hi k =
5353
if lo <= hi then
54-
let median = lo + (hi - lo) / 2
54+
let median = int ((uint32 hi + uint32 lo) >>> 1)
5555
match arr.[median].KeyTo.CompareTo k with
5656
| 0 -> median
5757
| x when x < 0 -> binarySearch (median + 1) hi k
@@ -87,8 +87,9 @@ type RangeMap<'key,'a when 'key :> IComparable<'key>> private(arr: RangeMapEleme
8787
// the next nearest element to be found. We also limit
8888
// it to the highest index in the array.
8989
| x -> Math.Min(~~~x, arr.Length - 1)
90-
if arr.[idx].KeyFrom.CompareTo k <= 0 && k.CompareTo arr.[idx].KeyTo <= 0 then
91-
ValueSome arr.[idx].Value
90+
let element = &arr.[idx]
91+
if element.KeyFrom.CompareTo k <= 0 && k.CompareTo element.KeyTo <= 0 then
92+
ValueSome element.Value
9293
else
9394
ValueNone
9495
/// A read-only span containing the elements of the range map.

0 commit comments

Comments
 (0)