Skip to content

Commit 1d3409c

Browse files
authored
Merge pull request #1439 from jackmott/comparewith
Removing recursion in array.fs where it is may be worthwhile
2 parents 2b306ad + d6c85ea commit 1d3409c

File tree

1 file changed

+31
-28
lines changed

1 file changed

+31
-28
lines changed

src/fsharp/FSharp.Core/array.fs

Lines changed: 31 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -85,22 +85,21 @@ namespace Microsoft.FSharp.Collections
8585
[<CompiledName("CopyTo")>]
8686
let inline blit (source : 'T[]) (sourceIndex:int) (target: 'T[]) (targetIndex:int) (count:int) =
8787
Array.Copy(source, sourceIndex, target, targetIndex, count)
88-
89-
let rec concatAddLengths (arrs:'T[][]) i acc =
90-
if i >= arrs.Length then acc
91-
else concatAddLengths arrs (i+1) (acc + arrs.[i].Length)
92-
93-
let rec concatBlit (arrs:'T[][]) i j (tgt:'T[]) =
94-
if i < arrs.Length then
95-
let h = arrs.[i]
96-
let len = h.Length
97-
Array.Copy(h, 0, tgt, j, len)
98-
concatBlit arrs (i+1) (j+len) tgt
88+
89+
let concatArrays (arrs : 'T[][]) : 'T[] =
90+
let mutable acc = 0
91+
for h in arrs do
92+
acc <- acc + h.Length
93+
94+
let res = Array.zeroCreateUnchecked acc
9995

100-
let concatArrays (arrs : 'T[][]) =
101-
let res = Array.zeroCreateUnchecked (concatAddLengths arrs 0 0)
102-
concatBlit arrs 0 0 res
103-
res
96+
let mutable j = 0
97+
for i = 0 to arrs.Length-1 do
98+
let h = arrs.[i]
99+
let len = h.Length
100+
Array.Copy(h,0,res,j,len)
101+
j <- j + len
102+
res
104103

105104
[<CompiledName("Concat")>]
106105
let concat (arrays: seq<'T[]>) =
@@ -988,22 +987,26 @@ namespace Microsoft.FSharp.Collections
988987
let inline compareWith (comparer:'T -> 'T -> int) (array1: 'T[]) (array2: 'T[]) =
989988
checkNonNull "array1" array1
990989
checkNonNull "array2" array2
991-
990+
992991
let length1 = array1.Length
993992
let length2 = array2.Length
994-
let minLength = Operators.min length1 length2
995-
996-
let rec loop index =
997-
if index = minLength then
998-
if length1 = length2 then 0
999-
elif length1 < length2 then -1
1000-
else 1
1001-
else
1002-
let result = comparer array1.[index] array2.[index]
1003-
if result <> 0 then result else
1004-
loop (index+1)
993+
994+
let mutable i = 0
995+
let mutable result = 0
996+
997+
if length1 < length2 then
998+
while i < array1.Length && result = 0 do
999+
result <- comparer array1.[i] array2.[i]
1000+
i <- i + 1
1001+
else
1002+
while i < array2.Length && result = 0 do
1003+
result <- comparer array1.[i] array2.[i]
1004+
i <- i + 1
10051005

1006-
loop 0
1006+
if result <> 0 then result
1007+
elif length1 = length2 then 0
1008+
elif length1 < length2 then -1
1009+
else 1
10071010

10081011
[<CompiledName("GetSubArray")>]
10091012
let sub (array:'T[]) (startIndex:int) (count:int) =

0 commit comments

Comments
 (0)