dotnet / dotnet/fsharp

Could the compiler utilize OptimizedClosures.FSharpFunc?

Open
#6,499 3 comments 0 reactions 0 assignees View on GitHub
Area-Compiler-Optimization Feature Improvement
Dominant language
F#
Stars
4.3k
Forks
876
Avg merge
4d 22h
Merged PRs (30d)
144

Description

I was doing some benchmarking today and was a bit surprised by some of the results.

The following function

```fsharp
let bar (f : 'a -> 'a -> 'a) (a:'a array) (b:'a array) =
Array.map2 f a b
```

is much faster than the next one, even though the previous one allocates a whole new array to store the results in.

```fsharp
let barInPlace (f : 'a -> 'a -> 'a) (a:'a array) (b:'a array) =
for i in 0..b.Length - 1 do
b.[i] <- f a.[i] b.[i]
```
In my case, I'd rather mutate one of the arrays instead of allocating a new one, since it can be quite large and `b` would be GC'd if not.

#### Repro steps

https://github.com/atlemann/OptimizedClosures

```bash
dotnet run -c Release -p OptimizedFunc.fsproj
```

#### Expected behavior

`barInPlace` to be faster than `bar`

#### Actual behavior

`bar` is much faster even though it allocates a whole new array

#### Known workarounds

Use OptimizedClosures.FSharpFunc in my own code, or inline all the things.

#### Related information

.NET Core SDK (reflecting any global.json):
Version: 2.2.104
Commit: 73f036d4ac

Runtime Environment:
OS Name: ubuntu
OS Version: 18.04
OS Platform: Linux
RID: ubuntu.18.04-x64

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.