Plotting with piecewise is slow

This drives me crazy. Why producing the first plot is so slow?

It is exactly same as the second plot except that the colors are not the same.

(The same slow it is with Plot[Evaluate@ Table[Piecewise[{{Sin[x] + n, -n < x < 1}, {I, True}}], {n, -20, 20}], {x, -21, 2}] // AbsoluteTiming).

Try with 0 instaed of I then it take 30 seconds.

pl = Table[
Piecewise[{{Sin[x] + n, -n < x < 1}, {I, True}}], {n, -20, 20}];
Plot[pl, {x, -21, 2}] // AbsoluteTiming
Plot[Table[
Piecewise[{{Sin[x] + n, -n < x < 1}, {I, True}}], {n, -20,
20}], {x, -21, 2}] // AbsoluteTiming


• Another variation: Plot[Table[ Piecewise[{{Sin[x] + n, -n < x < 1}, {I, True}}], {n, -20, 20}], {x, -21, 2}, Evaluated -> True] is fast with individually colored curves. Apr 21 at 20:34

Use Exclusions -> None to turn off detecting the discontinuities, or replace Piecewise with ConditionalExpression.

\$Version
(* "14.0.0 for Microsoft Windows (64-bit) (December 13, 2023)" *)

pl = Table[Piecewise[{{Sin[x] + n, -n < x < 1}, {I, True}}], {n, -20, 20}];

Plot[pl, {x, -21, 2}] // AbsoluteTiming // First
(* 0.403537*)

Plot[pl, {x, -21, 2}, Exclusions -> None] // AbsoluteTiming // First
(* 0.101821*)

pl2 = Table[ConditionalExpression[Sin[x] + n, -n < x < 1], {n, -20, 20}];
Plot[pl2, {x, -21, 2}, Exclusions -> None] // AbsoluteTiming // First
(* 0.0972942 *)

Plot[Table[Piecewise[{{Sin[x] + n, -n < x < 1}, {I, True}}], {n, -20,
20}], {x, -21, 2}] // AbsoluteTiming // First
(* 0.0820308 *)

• Note that Piecewise[{{Sin[x] + n, -n < x < 1}, {Undefined, True}}] evaluates to ConditionalExpression (thus yours is similar to azerbajdzan's). Apr 21 at 20:36
• Not sure what you mean. I don't have any Piecewise[..., Undefined] in my code :) Apr 21 at 21:07
• You have ConditionalExpression, azerbajdzan has the Piecewise code. Why did you think I was comparing yours and theirs? :) Anyway, it's mainly for others to point out how they are related. It doesn't seem to be well-known. :) :) Apr 22 at 0:17

Using Undefined instead of other values solves the problem. Anyway to me it is a bug.

Plot[Evaluate@
Table[Piecewise[{{Sin[x] + n, -n < x < 1}, {Undefined,
True}}], {n, -20, 20}], {x, -21, 2}] // AbsoluteTiming


• Yes it may be similar, I posted it before Domen's answer. Apr 21 at 20:33
• This bug have been fixed after version 14.0 Apr 22 at 0:28