Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop in list

Poeple often use

for i in [0 .. 10] do something

but afaik that creates a list which is then iterated through, it appears to me it would make more sense to use

for i = 0 to 10 do something

without creating that unnecessary list but having the same behaviour. Am I missing something? (I guess that's the case)

like image 577
Preza8 Avatar asked Nov 30 '22 00:11

Preza8


1 Answers

You are correct, writing for i in [0 .. 10] do something generates a list and it does have a significant overhead. Though you can also omit the square brackets, in which case it just builds a lazy sequence (and, it turns out that the compiler even optimizes that case). I generally prefer writing in 0 .. 100 do because it looks the same as code that iterates over a sequence.

Using the #time feature of F# interactive to do a simple analysis:

for i in [ 0 .. 10000000 ] do // 3194ms (yikes!)
  last <- i

for i in 0 .. 10000000 do     // 3ms
  last <- i

for i = 0 to 10000000 do      // 3ms
  last <- i

for i in seq { 0 .. 10000000 } do // 709ms (smaller yikes!)
  last <- i

So, it turns out that the compiler actually optimizes the in 0 .. 10000000 do into the same thing as the 0 to 10000000 do loop. You can force it to create the lazy sequence explicitly (last case) which is faster than a list, but still very slow.

like image 169
Tomas Petricek Avatar answered Dec 04 '22 14:12

Tomas Petricek