300 milliseconds just for declaring a variable in F # Interactive?

I play with the F # Interactive Console and compare the runtime of some numerical operations. In this code, the total runtime seems to double only by repeating the declaration of a single variable.

In VS 2010, I:

open System.Diagnostics let mutable a=1 

Then I select this below and run it with Alt + Enter

 let stopWatch = Stopwatch.StartNew() for i=1 to 200100100 do a <- a + 1 stopWatch.Stop() printfn "stopWatch.Elapsed: %f" stopWatch.Elapsed.TotalMilliseconds 

More or less required: 320 ms

Now I select this and press Alt + Enter:

 let mutable a=1 let stopWatch = Stopwatch.StartNew() for i=1 to 200100100 do a <- a + 1 stopWatch.Stop() printfn "stopWatch.Elapsed: %f" stopWatch.Elapsed.TotalMilliseconds 

almost double: 620 ms

The same block, but containing the declaration at the top, almost doubles. Shouldn't this be the same since I declare a variable before the stopwatch .StartNew ()? Is it connected to an interactive console? I have the same results using the #time directive.

+4
source share
2 answers

I am not sure that any of the answers is still right. I think a seems the same in both cases. And by that I mean that the individual type is emitted dynamically, wrapping this mutable value (of course, in a bunch!). This must be done, since in both cases a is a binding at the upper level, which can be addressed by subsequent interactions.

So, all that was said, my theory is this: in the first case, the dynamic type emitted by the FSI is loaded at the end of the interaction to display its default value. In the second case, however, a wrapper of type a not loaded until it is first available, in a loop after starting StopWatch .

+4
source

Daniel is right - if you define a variable in a separate FSI interaction, then it appears differently.

To get the correct comparison, you need to declare the variable as local in both cases. The easiest way to do this is to paste the code under do (which turns everything under do into a local area), and then evaluate the entire do block at once. See the Result of the following two examples:

 // A version with variable declaration excluded do let mutable a=1 let stopWatch = Stopwatch.StartNew() for i=1 to 200100100 do a <- a + 1 stopWatch.Stop() printfn "stopWatch.Elapsed: %f" stopWatch.Elapsed.TotalMilliseconds // A version with variable declaration included do let stopWatch = Stopwatch.StartNew() let mutable a=1 for i=1 to 200100100 do a <- a + 1 stopWatch.Stop() printfn "stopWatch.Elapsed: %f" stopWatch.Elapsed.TotalMilliseconds 

The difference that I get at startup is not measurable.

+3
source

All Articles