Are `const` declarations required in Pluto?

Are const declaration necessary in Pluto?

Since one cannot redefine the variables, I wander if everything is const (and thus type-stable) already (thus making the notebook cleaner).

It is not clear to me, this for example shows no difference:

While in the REPL there is a difference, but also both executions are much faster (is this normal, to have slower execution inside Pluto in general?):

julia> v1 = rand(1000);

julia> test1() = sum(v1)
test1 (generic function with 1 method)

julia> @btime test1()
  88.915 ns (1 allocation: 16 bytes)
502.54604012034895

julia> const v2 = copy(v1);

julia> test2() = sum(v2);

julia> @btime test2()
  68.248 ns (0 allocations: 0 bytes)
502.54604012034895


@btime gives you the result of your calculation in Pluto, not the time. The execution time is printed to the REPL.
If you want the timing, use @belapsed or @benchmark.

This said, Pluto implicitly wraps some cells into functions, therefore some commands relying on global variables are faster than in the REPL. Not sure if this is here the case.

1 Like

Ah, thanks for pointed that (stupid) mistake of mine in reading the output.

Anyway, I’m seeing significant performance differences between the code run in Pluto and in the REPL (in Pluto being slower). Also, the performance is dependent on declaring some variables as consts or not. I’ m using closures, so may be this is related to the issue:

Well, this makes the case that consts are needed in this case, at least:

So probably there is where I’m having my performance issues. Normally I wouldn’t use these closures outside functions for these reasons, but in a notebook sometimes the flow is more natural by doing things at the global scope. I thought for a moment that Pluto could take care of that because of how it works.

If you define the closure in a separate cell, it is fast again in Pluto because Pluto wraps the closure implicitly in a function which makes it type-stable.

This wrapping is not done for the closure which is interpolated with BenchmarkTools.

For the first 2 benchmarks, I get the same timings in Pluto and in the REPL.
For the last version, the REPL is slower, comparable to the type-unstable version 1 (whereas Pluto is as fast as the type-stable version 2).

1 Like

Uhm…yes. But only the “closure like syntax” works in this case (meaning that f = x -> c*x^2 and f(x) = c*x^2 behave differently in Pluto than in the REPL. Some care has to be taken with that:

(in the REPL these are both type unstable and have to be fixed by const c, while in PLUTO one has to do that only for the f_test(x) = c*x^2 syntax).

1 Like

I think Pluto does not wrap function definitions in functions, only “normal” fields.

1 Like