Skip to content

Using for-loops with the ".." operator produces suboptimal code #9548

Closed
@teo-tsirpanis

Description

@teo-tsirpanis

Consider the following snippet:

open System

let f() =
  for x in 0 .. 15 do
    Console.WriteLine x

It produces a nice, C#esque for-loop. Now consider this one:

open System

let g() =
  for x in 0 .. 2 .. 15 do
    Console.WriteLine x

It creates a sequence and then enumerates it. And it also has a consecutive pair of ldnull; pop; twice, as well as a needless unit local.

Producing a for (int i = 0; i < 15; i += 2) in the second case would have been much more efficient. We could even generalize it to arbitrary types with an addition operator, not just ints. Furthermore, in the first example, replacing the loop with for x in 0.0 .. 15.0 creates a sequence too.

In addition, using like for x in [0 .. 15] does correctly produce a list, but the compiler should warn to better remove the brackets when using a ranged list literal in a loop.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Done

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions