Skip to content

Commit affc14d

Browse files
Reduce allocations in some Array.Parallel funcs
1 parent ccee270 commit affc14d

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

src/FSharp.Core/array.fs

+16-11
Original file line numberDiff line numberDiff line change
@@ -2179,9 +2179,8 @@ module Array =
21792179
// Not exists $condition <==> (opposite of $condition is true forall)
21802180
exists (predicate >> not) array |> not
21812181

2182-
[<CompiledName("TryFindIndex")>]
2183-
let tryFindIndex predicate (array: _ array) =
2184-
checkNonNull "array" array
2182+
let inline tryFindIndexAux predicate (array: _ array) =
2183+
checkNonNull (nameof array) array
21852184

21862185
let pResult =
21872186
Parallel.For(
@@ -2192,32 +2191,38 @@ module Array =
21922191
pState.Break())
21932192
)
21942193

2195-
pResult.LowestBreakIteration |> Option.ofNullable |> Option.map int
2194+
pResult.LowestBreakIteration
2195+
2196+
[<CompiledName("TryFindIndex")>]
2197+
let tryFindIndex predicate (array: _ array) =
2198+
let i = tryFindIndexAux predicate array
2199+
if i.HasValue then Some (int (i.GetValueOrDefault()))
2200+
else None
21962201

21972202
[<CompiledName("TryFind")>]
21982203
let tryFind predicate (array: _ array) =
2199-
array |> tryFindIndex predicate |> Option.map (fun i -> array[i])
2204+
let i = tryFindIndexAux predicate array
2205+
if i.HasValue then Some array[int (i.GetValueOrDefault())]
2206+
else None
22002207

22012208
[<CompiledName("TryPick")>]
22022209
let tryPick chooser (array: _ array) =
22032210
checkNonNull "array" array
2204-
let allChosen = new System.Collections.Concurrent.ConcurrentDictionary<_, _>()
2211+
let mutable chosen = None
22052212

2206-
let pResult =
2213+
let _pResult =
22072214
Parallel.For(
22082215
0,
22092216
array.Length,
22102217
(fun i pState ->
22112218
match chooser array[i] with
22122219
| None -> ()
22132220
| chosenElement ->
2214-
allChosen[i] <- chosenElement
2221+
ignore (Interlocked.Exchange(&chosen, chosenElement))
22152222
pState.Break())
22162223
)
22172224

2218-
pResult.LowestBreakIteration
2219-
|> Option.ofNullable
2220-
|> Option.bind (fun i -> allChosen[int i])
2225+
chosen
22212226

22222227
[<CompiledName("Choose")>]
22232228
let choose chooser (array: 'T array) =

0 commit comments

Comments
 (0)