Skip to content

Commit

Permalink
Improve speed of GetHashCode
Browse files Browse the repository at this point in the history
  • Loading branch information
HLWeil committed Feb 13, 2024
1 parent fdc8b5f commit 8635d76
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 10 deletions.
13 changes: 3 additions & 10 deletions src/ISA/ISA/ArcTypes/ArcTable.fs
Original file line number Diff line number Diff line change
Expand Up @@ -780,18 +780,11 @@ type ArcTable(name: string, headers: ResizeArray<CompositeHeader>, values: Syste
// it's good practice to ensure that this behaves using the same fields as Equals does:
override this.GetHashCode() =
//let v1,v2 =
let v =
[|
for KeyValue(k,v) in this.Values do
yield k, v
|]
|> Array.sortBy fst
// must remove tuples. Tuples handle unpredictable for GetHashCode in javascript.
|> Array.map (fun ((k1,k2),v) -> [|box k1; box k2; box v|] |> Aux.HashCodes.boxHashArray)
let vHash = ArcTableAux.boxHashValues this.ColumnCount this.Values
[|
box this.Name
Array.ofSeq >> Aux.HashCodes.boxHashArray <| this.Headers
Array.ofSeq >> Aux.HashCodes.boxHashArray <| v
this.Headers |> Aux.HashCodes.boxHashSeq
vHash
|]
|> Aux.HashCodes.boxHashArray
|> fun x -> x :?> int
9 changes: 9 additions & 0 deletions src/ISA/ISA/ArcTypes/ArcTableAux.fs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ let getRowCount (values:Dictionary<int*int,CompositeCell>) =
if values.Count = 0 then 0 else
values.Keys |> Seq.maxBy snd |> snd |> (+) 1

let boxHashValues colCount (values:Dictionary<int*int,CompositeCell>) =
let mutable hash = 0
let rowCount = getRowCount values
for col = 0 to colCount - 1 do
for row = 0 to rowCount - 1 do
hash <- 0x9e3779b9 + values.[col,row].GetHashCode() + (hash <<< 6) + (hash >>> 2)
hash
|> box

// TODO: Move to CompositeHeader?
let (|IsUniqueExistingHeader|_|) existingHeaders (input: CompositeHeader) =
match input with
Expand Down
7 changes: 7 additions & 0 deletions tests/ISA/ISA.Tests/ArcTable.Tests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,13 @@ let private tests_GetHashCode = testList "GetHashCode" [
let notActual = create_testTable()
Expect.notEqual actual notActual "equal"
Expect.notEqual (actual.GetHashCode()) (notActual.GetHashCode()) "Hash"
testCase "Performance" <| fun _ ->
let testTable = ArcTable.init("Test")
let values = Array.init 10000 (fun i -> CompositeCell.createFreeText (string i))
testTable.AddColumn(CompositeHeader.FreeText "Header", values)
let f1 () = testTable.GetHashCode()
// On i7-13800H, 2ms in Dotnet and 18ms in javascript
Expect.wantFaster f1 50 "GetHashCode is too slow" |> ignore
]

let private tests_validate =
Expand Down

0 comments on commit 8635d76

Please sign in to comment.