pine-script

Boolean expression evaluation and performance


I think there's a flaw in the way that Pine Script evaluates boolean expressions, that can hugely affect performance.

See this example

//@version=4
study("PlayGround", overlay=true)

var int y = 0

f1() =>
    label.new(bar_index, high)
    true

if false and f1()
    y := y + 1

plot(y, title="y")

The statement if false and f1() should not need to evaluate the outcome of function f1() in order to know that the result will always be false.
However - as demonstrated by the fact that labels are drawn on the chart - the function f1() is still executed on every bar.
So Pine Script seems to evaluate the entire expression before making a decision, which is unnecessary.

Don't know if this is by design, but I think this should be corrected.

Contextual info
I have a script that contains a huge number of consecutive if statements to check wether the current bar is on a certain date.
In an attempt to improve the performance, I added a boolean variable to be evaluated first on each if statement.
(an example can be seen in the f_prediction_daily() function in Plotting custom data - daily = ok, weekly = not ok)
But as my list of if statements grew larger I noticed a decrease in performance.
Therefore, I've created this little test and question.


Solution

  • Correct. The evaluation of boolean expressions does not currently short-circuit in Pine, so all elements in the expression are evaluated.