From aab0ae24761e435f738b945c760680cc295c1469 Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 23 Mar 2024 15:14:10 +0100 Subject: [PATCH] Some minor perf improvements --- src/Compiler/AbstractIL/ilwrite.fs | 2 +- src/Compiler/Driver/CompilerDiagnostics.fs | 5 +++-- src/Compiler/Driver/CreateILModule.fs | 5 +++-- src/Compiler/Facilities/DiagnosticsLogger.fs | 5 +++-- src/Compiler/Facilities/DiagnosticsLogger.fsi | 2 +- src/Compiler/Service/TransparentCompiler.fs | 2 +- src/Compiler/TypedTree/TypedTree.fs | 2 +- src/Compiler/Utilities/LruCache.fs | 6 +++--- src/Compiler/Utilities/illib.fs | 17 ++++++++-------- src/Compiler/Utilities/illib.fsi | 4 ++-- src/Compiler/Utilities/lib.fs | 4 +++- src/Compiler/pars.fsy | 2 +- src/fsi/console.fs | 13 ++++-------- .../Types/UnionTypes/UnionStructTypes.fs | 2 +- .../Graph/FileContentMappingTests.fs | 20 +++++++++++-------- .../BuildGraphTests.fs | 6 +++--- tests/FSharp.Test.Utilities/CompilerAssert.fs | 2 +- tests/scripts/scriptlib.fsx | 6 +++--- tests/service/ProjectAnalysisTests.fs | 2 +- 19 files changed, 56 insertions(+), 51 deletions(-) diff --git a/src/Compiler/AbstractIL/ilwrite.fs b/src/Compiler/AbstractIL/ilwrite.fs index f41c8aaa08d..1b23edd2f7e 100644 --- a/src/Compiler/AbstractIL/ilwrite.fs +++ b/src/Compiler/AbstractIL/ilwrite.fs @@ -3215,7 +3215,7 @@ let count f arr = module FileSystemUtilities = open System.Reflection open System.Globalization - let progress = try Environment.GetEnvironmentVariable("FSharp_DebugSetFilePermissions") <> null with _ -> false + let progress = try not (isNull (Environment.GetEnvironmentVariable("FSharp_DebugSetFilePermissions"))) with _ -> false /// Arbitrary value [] diff --git a/src/Compiler/Driver/CompilerDiagnostics.fs b/src/Compiler/Driver/CompilerDiagnostics.fs index 596ea9f085d..823eb4ccbf1 100644 --- a/src/Compiler/Driver/CompilerDiagnostics.fs +++ b/src/Compiler/Driver/CompilerDiagnostics.fs @@ -616,10 +616,11 @@ module OldStyleMessages = let mutable showParserStackOnParseError = false #endif +[] let (|InvalidArgument|_|) (exn: exn) = match exn with - | :? ArgumentException as e -> Some e.Message - | _ -> None + | :? ArgumentException as e -> ValueSome e.Message + | _ -> ValueNone let OutputNameSuggestions (os: StringBuilder) suggestNames suggestionsF idText = if suggestNames then diff --git a/src/Compiler/Driver/CreateILModule.fs b/src/Compiler/Driver/CreateILModule.fs index 04cda7f6c3f..506171ed0ef 100644 --- a/src/Compiler/Driver/CreateILModule.fs +++ b/src/Compiler/Driver/CreateILModule.fs @@ -54,11 +54,12 @@ module AttributeHelpers = | Some(Attrib(_, _, [ AttribBoolArg p ], _, _, _, _)) -> Some p | _ -> None + [] let (|ILVersion|_|) (versionString: string) = try - Some(parseILVersion versionString) + ValueSome(parseILVersion versionString) with e -> - None + ValueNone //---------------------------------------------------------------------------- // ValidateKeySigningAttributes, GetStrongNameSigner diff --git a/src/Compiler/Facilities/DiagnosticsLogger.fs b/src/Compiler/Facilities/DiagnosticsLogger.fs index d93a3a60b6c..443282ffe95 100644 --- a/src/Compiler/Facilities/DiagnosticsLogger.fs +++ b/src/Compiler/Facilities/DiagnosticsLogger.fs @@ -69,10 +69,11 @@ exception StopProcessingExn of exn option with | StopProcessingExn(Some exn) -> "StopProcessingExn, originally (" + exn.ToString() + ")" | _ -> "StopProcessingExn" +[] let (|StopProcessing|_|) exn = match exn with - | StopProcessingExn _ -> Some() - | _ -> None + | StopProcessingExn _ -> ValueSome() + | _ -> ValueNone let StopProcessing<'T> = StopProcessingExn None diff --git a/src/Compiler/Facilities/DiagnosticsLogger.fsi b/src/Compiler/Facilities/DiagnosticsLogger.fsi index ec2d37bc040..66b759726aa 100644 --- a/src/Compiler/Facilities/DiagnosticsLogger.fsi +++ b/src/Compiler/Facilities/DiagnosticsLogger.fsi @@ -39,7 +39,7 @@ val NoSuggestions: Suggestions /// Thrown when we stop processing the F# Interactive entry or #load. exception StopProcessingExn of exn option -val (|StopProcessing|_|): exn: exn -> unit option +val (|StopProcessing|_|): exn: exn -> unit voption val StopProcessing<'T> : exn diff --git a/src/Compiler/Service/TransparentCompiler.fs b/src/Compiler/Service/TransparentCompiler.fs index 679c0d46d3f..972ef28182a 100644 --- a/src/Compiler/Service/TransparentCompiler.fs +++ b/src/Compiler/Service/TransparentCompiler.fs @@ -1155,7 +1155,7 @@ type internal TransparentCompiler //Trace.TraceInformation("\n" + debugGraph) - if Activity.Current <> null then + if not (isNull (Activity.Current)) then Activity.Current.AddTag("graph", debugGraph) |> ignore return nodeGraph, graph diff --git a/src/Compiler/TypedTree/TypedTree.fs b/src/Compiler/TypedTree/TypedTree.fs index 7c2a454ae36..df66709ce90 100644 --- a/src/Compiler/TypedTree/TypedTree.fs +++ b/src/Compiler/TypedTree/TypedTree.fs @@ -5933,7 +5933,7 @@ type Construct() = match baseType with | null -> false | x when x.IsGenericType -> false - | x when x.DeclaringType <> null -> false + | x when not (isNull (x.DeclaringType)) -> false | x -> x.FullName = "System.Delegate" || x.FullName = "System.MulticastDelegate"), m)) IsEnum = st.PUntaint((fun st -> st.IsEnum), m) IsStructOrEnum = st.PUntaint((fun st -> st.IsValueType || st.IsEnum), m) diff --git a/src/Compiler/Utilities/LruCache.fs b/src/Compiler/Utilities/LruCache.fs index 62abc1d829c..139513e7956 100644 --- a/src/Compiler/Utilities/LruCache.fs +++ b/src/Compiler/Utilities/LruCache.fs @@ -36,7 +36,7 @@ type internal LruCache<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVers let weakList = LinkedList<'TKey * 'TVersion * string * ValueLink<'TValue>>() let rec removeCollected (node: LinkedListNode<_>) = - if node <> null then + if not (isNull node) then let key, version, label, value = node.Value match value with @@ -63,7 +63,7 @@ type internal LruCache<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVers let mutable node = weakList.Last - while weakList.Count > keepWeakly && node <> null do + while weakList.Count > keepWeakly && not (isNull node) do let previous = node.Previous let key, version, label, _ = node.Value weakList.Remove node @@ -80,7 +80,7 @@ type internal LruCache<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVers let mutable anythingWeakened = false - while strongList.Count > keepStrongly && node <> null do + while strongList.Count > keepStrongly && not (isNull node) do let previous = node.Previous match node.Value with diff --git a/src/Compiler/Utilities/illib.fs b/src/Compiler/Utilities/illib.fs index fca3cd54605..ad41d74c0de 100644 --- a/src/Compiler/Utilities/illib.fs +++ b/src/Compiler/Utilities/illib.fs @@ -639,8 +639,7 @@ module List = let duplicates (xs: 'T list) = xs |> List.groupBy id - |> List.filter (fun (_, elems) -> Seq.length elems > 1) - |> List.map fst + |> List.choose (fun (key, elems) -> if Seq.length elems > 1 then Some key else None) let internal allEqual (xs: 'T list) = match xs with @@ -802,15 +801,17 @@ module String = /// Splits a string into substrings based on the strings in the array separators let split options (separator: string[]) (value: string) = value.Split(separator, options) + [] let (|StartsWith|_|) pattern value = - if String.IsNullOrWhiteSpace value then None - elif value.StartsWithOrdinal pattern then Some() - else None + if String.IsNullOrWhiteSpace value then ValueNone + elif value.StartsWithOrdinal pattern then ValueSome() + else ValueNone + [] let (|Contains|_|) pattern value = - if String.IsNullOrWhiteSpace value then None - elif value.Contains pattern then Some() - else None + if String.IsNullOrWhiteSpace value then ValueNone + elif value.Contains pattern then ValueSome() + else ValueNone let getLines (str: string) = use reader = new StringReader(str) diff --git a/src/Compiler/Utilities/illib.fsi b/src/Compiler/Utilities/illib.fsi index a9ee48c4be9..a537d0ecbb5 100644 --- a/src/Compiler/Utilities/illib.fsi +++ b/src/Compiler/Utilities/illib.fsi @@ -296,9 +296,9 @@ module internal String = /// Splits a string into substrings based on the strings in the array separators val split: options: StringSplitOptions -> separator: string[] -> value: string -> string[] - val (|StartsWith|_|): pattern: string -> value: string -> unit option + val (|StartsWith|_|): pattern: string -> value: string -> unit voption - val (|Contains|_|): pattern: string -> value: string -> unit option + val (|Contains|_|): pattern: string -> value: string -> unit voption val getLines: str: string -> string[] diff --git a/src/Compiler/Utilities/lib.fs b/src/Compiler/Utilities/lib.fs index 87e50acd74a..b9c6456a205 100755 --- a/src/Compiler/Utilities/lib.fs +++ b/src/Compiler/Utilities/lib.fs @@ -312,7 +312,9 @@ type Graph<'Data, 'Id when 'Id : comparison and 'Id : equality> let tab = Map.ofList nodes let nodes = List.map snd nodes do for node in nodes do - node.nodeNeighbours <- edges |> List.filter (fun (x, _y) -> x = node.nodeId) |> List.map (fun (_, nodeId) -> tab[nodeId]) + node.nodeNeighbours <- + edges + |> List.choose (fun (x, nodeId) -> if x = node.nodeId then Some tab[nodeId] else None) member g.GetNodeData nodeId = tab[nodeId].nodeData diff --git a/src/Compiler/pars.fsy b/src/Compiler/pars.fsy index b1b4f43a473..b22281909e3 100644 --- a/src/Compiler/pars.fsy +++ b/src/Compiler/pars.fsy @@ -6633,7 +6633,7 @@ nameop: identExpr: | ident - { if $1.idText = "" then + { if System.String.IsNullOrEmpty $1.idText then SynExpr.FromParseError(SynExpr.Ident($1), $1.idRange) else SynExpr.Ident($1) } diff --git a/src/fsi/console.fs b/src/fsi/console.fs index 0c1f056533d..388a26c0510 100644 --- a/src/fsi/console.fs +++ b/src/fsi/console.fs @@ -31,16 +31,11 @@ type internal History() = current <- -1 member _.Add line = - match line with - | null - | "" -> () - | _ -> list.Add(line) + if not (String.IsNullOrWhiteSpace line) then + list.Add line member _.AddLast line = - match line with - | null - | "" -> () - | _ -> + if not (String.IsNullOrWhiteSpace line) then list.Add(line) current <- list.Count @@ -539,7 +534,7 @@ type internal ReadLineConsole() = let previous = history.Previous() history.Next() |> ignore - if previous = "" then + if String.IsNullOrEmpty previous then setPrompt true else setPrompt (previous.EndsWith(";;")) diff --git a/tests/FSharp.Compiler.ComponentTests/Conformance/Types/UnionTypes/UnionStructTypes.fs b/tests/FSharp.Compiler.ComponentTests/Conformance/Types/UnionTypes/UnionStructTypes.fs index 630d2c2a838..5d71b240abc 100644 --- a/tests/FSharp.Compiler.ComponentTests/Conformance/Types/UnionTypes/UnionStructTypes.fs +++ b/tests/FSharp.Compiler.ComponentTests/Conformance/Types/UnionTypes/UnionStructTypes.fs @@ -695,7 +695,7 @@ type StructUnion = for i=1 to countOfCases do let t = basicTypes[i%basicTypes.Length] - if t = "" then + if System.String.IsNullOrEmpty t then codeSb.AppendLine($" | Case{i}") |> ignore else codeSb.AppendLine($" | Case{i} of field1_{i}:{t} * field2_{i}:{t}") |> ignore diff --git a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/FileContentMappingTests.fs b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/FileContentMappingTests.fs index 12f171de5fa..1d1b3d5c892 100644 --- a/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/FileContentMappingTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/TypeChecks/Graph/FileContentMappingTests.fs @@ -9,31 +9,35 @@ let private getContent isSignature sourceCode = let ast = parseSourceCode ("Test.fs", sourceCode) FileContentMapping.mkFileContent { Idx = 0; FileName = fileName; ParsedInput = ast } +[] let private (|TopLevelNamespace|_|) value e = match e with | FileContentEntry.TopLevelNamespace(path, content) -> let combined = String.concat "." path - if combined = value then Some content else None - | _ -> None + if combined = value then ValueSome content else ValueNone + | _ -> ValueNone +[] let private (|OpenStatement|_|) value e = match e with | FileContentEntry.OpenStatement path -> let combined = String.concat "." path - if combined = value then Some() else None - | _ -> None + if combined = value then ValueSome() else ValueNone + | _ -> ValueNone +[] let private (|PrefixedIdentifier|_|) value e = match e with | FileContentEntry.PrefixedIdentifier path -> let combined = String.concat "." path - if combined = value then Some() else None - | _ -> None + if combined = value then ValueSome() else ValueNone + | _ -> ValueNone +[] let private (|NestedModule|_|) value e = match e with - | FileContentEntry.NestedModule(name, nestedContent) -> if name = value then Some(nestedContent) else None - | _ -> None + | FileContentEntry.NestedModule(name, nestedContent) -> if name = value then ValueSome(nestedContent) else ValueNone + | _ -> ValueNone [] let ``Top level module only exposes namespace`` () = diff --git a/tests/FSharp.Compiler.UnitTests/BuildGraphTests.fs b/tests/FSharp.Compiler.UnitTests/BuildGraphTests.fs index d07b23a5e99..0e60a0fffb6 100644 --- a/tests/FSharp.Compiler.UnitTests/BuildGraphTests.fs +++ b/tests/FSharp.Compiler.UnitTests/BuildGraphTests.fs @@ -17,7 +17,7 @@ module BuildGraphTests = let private createNode () = let o = obj () GraphNode(node { - Assert.shouldBeTrue (o <> null) + Assert.shouldBeTrue (not (isNull o)) return 1 }), WeakReference(o) @@ -149,7 +149,7 @@ module BuildGraphTests = | :? OperationCanceledException as ex -> ex - Assert.shouldBeTrue(ex <> null) + Assert.shouldBeTrue(not (isNull ex)) [] let ``A request can cancel 2``() = @@ -179,7 +179,7 @@ module BuildGraphTests = | :? OperationCanceledException as ex -> ex - Assert.shouldBeTrue(ex <> null) + Assert.shouldBeTrue(not (isNull ex)) try task.Wait(1000) |> ignore with | :? TimeoutException -> reraise() | _ -> () [] diff --git a/tests/FSharp.Test.Utilities/CompilerAssert.fs b/tests/FSharp.Test.Utilities/CompilerAssert.fs index a97b214acde..85c24828d9f 100644 --- a/tests/FSharp.Test.Utilities/CompilerAssert.fs +++ b/tests/FSharp.Test.Utilities/CompilerAssert.fs @@ -619,7 +619,7 @@ module rec CompilerAssertHelpers = func () true, None with e -> - let errorMessage = if e.InnerException <> null then e.InnerException.ToString() else e.ToString() + let errorMessage = if not (isNull (e.InnerException)) then e.InnerException.ToString() else e.ToString() stderr.Append errorMessage |> ignore false, Some e finally diff --git a/tests/scripts/scriptlib.fsx b/tests/scripts/scriptlib.fsx index b074b78ba25..357d2907c60 100644 --- a/tests/scripts/scriptlib.fsx +++ b/tests/scripts/scriptlib.fsx @@ -17,7 +17,7 @@ module Scripting = let executeProcess fileName arguments = let processWriteMessage (chan:TextWriter) (message:string) = - if message <> null then + if not (isNull message) then chan.WriteLine(message) printfn "%s %s" fileName arguments let info = ProcessStartInfo(Arguments=arguments, UseShellExecute=false, @@ -122,7 +122,7 @@ module Scripting = cmdArgs.RedirectOutput|> Option.iter (fun f -> processInfo.RedirectStandardOutput <- true p.OutputDataReceived.Add (fun ea -> - if ea.Data <> null then + if not (isNull (ea.Data)) then out.Append(ea.Data + Environment.NewLine) |> ignore f ea.Data) ) @@ -130,7 +130,7 @@ module Scripting = cmdArgs.RedirectError |> Option.iter (fun f -> processInfo.RedirectStandardError <- true p.ErrorDataReceived.Add (fun ea -> - if ea.Data <> null then + if not (isNull (ea.Data)) then err.Append(ea.Data + Environment.NewLine) |> ignore f ea.Data) ) diff --git a/tests/service/ProjectAnalysisTests.fs b/tests/service/ProjectAnalysisTests.fs index 5b8da7c30a3..27f285c13f4 100644 --- a/tests/service/ProjectAnalysisTests.fs +++ b/tests/service/ProjectAnalysisTests.fs @@ -9,7 +9,7 @@ module Tests.Service.ProjectAnalysisTests #nowarn "57" // Experimental stuff -let runningOnMono = try System.Type.GetType("Mono.Runtime") <> null with e -> false +let runningOnMono = try not (isNull (System.Type.GetType("Mono.Runtime"))) with e -> false open NUnit.Framework open FsUnit