# Plot of Piecewise function is slow

While working on answer for question (here) I found out that the Plot is incredible slow for Piecewise function:

Some preparations:

\[ScriptCapitalD]1 =
TransformedDistribution[Log[u],
u \[Distributed] UniformDistribution[{1, 2}]]
(* TransformedDistribution[
Log[\[FormalX]], \[FormalX] \[Distributed]
UniformDistribution[{1, 2}]] *)

\[ScriptCapitalD] =
TransformedDistribution[
u + v, {u \[Distributed] UniformDistribution[{1, 2}],
v \[Distributed] \[ScriptCapitalD]1}]
(* TransformedDistribution[
u + v, {u \[Distributed] UniformDistribution[{1, 2}],
v \[Distributed]
TransformedDistribution[
Log[\[FormalX]], \[FormalX] \[Distributed]
UniformDistribution[{1, 2}]]}] *)


This looks perfectly fine:

s[x_] := PDF[\[ScriptCapitalD], x]
pw[x_] := PiecewiseExpand[s[x], 1 <= x <= 2]
pw[x] // InputForm
(* Piecewise[{{1, x >= 1 + Log[2]}, {(-E + E^x)/E, Inequality[1, Less, x, Less,
1 + Log[2]]}}, 0] *)


But, the Plot is extremely slow and never finishes:

Plot[pw[x], {x, 1, 2}]


But, if I copy InputForm of pw, it magically started working:

pw2[x_] :=
Piecewise[{{1, x >= 1 + Log[2]}, {(-E + E^x)/E,
Inequality[1, Less, x, Less, 1 + Log[2]]}}, 0]

Plot[pw2[x], {x, 1, 2}]
(* produces plot *)


Using Mathematica 12.1.

• If you had done pw[x_] = PiecewiseExpand[s[x], 1 <= x <= 2] (i.e. use Set[] instead of SetDelayed[]), you would not have encountered this problem. Apr 17, 2020 at 13:44

 Plot[Evaluate@pw[x], {x, 1, 2}]

• Ok, it works. But why? I can't see Piecewise having any Hold. Apr 15, 2020 at 17:01
• @m0nhawk plot has Hold property. Plot has attribute HoldAll and evaluates f only after assigning specific numerical values to x. Apr 15, 2020 at 17:03