Skip to content

String mapi ~2.5x perf improvement #9474

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,4 @@ msbuild.binlog
/tests/fsharp/regression/5531/compilation.output.test.txt
/tests/fsharp/core/fsfromfsviacs/compilation.langversion.old.output.txt
/tests/fsharp/core/fsfromfsviacs/compilation.errors.output.txt
*.user
27 changes: 19 additions & 8 deletions src/fsharp/FSharp.Core/string.fs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ namespace Microsoft.FSharp.Core
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
[<RequireQualifiedAccess>]
module String =
[<CompiledName("Length")>]
let length (str:string) = if isNull str then 0 else str.Length

[<CompiledName("Concat")>]
let concat sep (strings : seq<string>) =
String.Join(sep, strings)
Expand Down Expand Up @@ -40,13 +43,24 @@ namespace Microsoft.FSharp.Core

[<CompiledName("MapIndexed")>]
let mapi (mapping: int -> char -> char) (str:string) =
if String.IsNullOrEmpty str then
let len = length str
if len = 0 then
String.Empty
else
let res = StringBuilder str.Length
let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(mapping)
str |> iteri (fun i c -> res.Append(f.Invoke(i, c)) |> ignore)
res.ToString()
let result = str.ToCharArray()
let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt mapping

// x2 unrolled loop gives 10-20% boost, overall 2.5x SB perf
let mutable i = 0
while i < len - len % 2 do
result.[i] <- f.Invoke(i, result.[i])
result.[i + 1] <- f.Invoke(i, result.[i + 1])
i <- i + 2

if i % 2 = 1 then
result.[i] <- f.Invoke(i, result.[i])

new String(result)

[<CompiledName("Filter")>]
let filter (predicate: char -> bool) (str:string) =
Expand Down Expand Up @@ -101,6 +115,3 @@ namespace Microsoft.FSharp.Core
else
let rec check i = (i < str.Length) && (predicate str.[i] || check (i+1))
check 0

[<CompiledName("Length")>]
let length (str:string) = if isNull str then 0 else str.Length