diff --git a/src/fsharp/FSharp.Core/array.fs b/src/fsharp/FSharp.Core/array.fs index f9cced85d3b..b92e3d95034 100644 --- a/src/fsharp/FSharp.Core/array.fs +++ b/src/fsharp/FSharp.Core/array.fs @@ -405,10 +405,12 @@ namespace Microsoft.FSharp.Collections loop 0 let inline groupByImpl (comparer:IEqualityComparer<'SafeKey>) (keyf:'T->'SafeKey) (getKey:'SafeKey->'Key) (array: 'T[]) = + let length = array.Length + if length = 0 then Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked 0 else let dict = Dictionary<_,ResizeArray<_>> comparer // Build the groupings - for i = 0 to (array.Length - 1) do + for i = 0 to length - 1 do let v = array.[i] let safeKey = keyf v let mutable prev = Unchecked.defaultof<_> diff --git a/src/fsharp/FSharp.Core/local.fs b/src/fsharp/FSharp.Core/local.fs index 779b543cd21..42297795184 100644 --- a/src/fsharp/FSharp.Core/local.fs +++ b/src/fsharp/FSharp.Core/local.fs @@ -196,6 +196,10 @@ module internal List = cons let groupBy (comparer:IEqualityComparer<'SafeKey>) (keyf:'T->'SafeKey) (getKey:'SafeKey->'Key) (list: 'T list) = + match list with + | [] -> [] + | _ -> + let dict = Dictionary<_, _ list []> comparer // Build the groupings diff --git a/src/fsharp/FSharp.Core/seq.fs b/src/fsharp/FSharp.Core/seq.fs index f057e8f3fd0..f8ef697a8e5 100644 --- a/src/fsharp/FSharp.Core/seq.fs +++ b/src/fsharp/FSharp.Core/seq.fs @@ -1032,6 +1032,8 @@ namespace Microsoft.FSharp.Collections let inline groupByImpl (comparer:IEqualityComparer<'SafeKey>) (keyf:'T->'SafeKey) (getKey:'SafeKey->'Key) (seq:seq<'T>) = checkNonNull "seq" seq + if isEmpty seq then empty else + let dict = Dictionary<_,ResizeArray<_>> comparer // Previously this was 1, but I think this is rather stingy, considering that we are already paying