sesto1
Pine Script Rookie
Pine Script Rookie
Posts: 1
Joined: October 21st, 2021

Efficiency of code

Hello,

as a complete newbie I have put together my first script (thx to Mathew), which is about 300 lines long and now I would like to modify it so that it compiles as efficiently as possible. So my question is what is better/more efficient (thus also faster when changing the user inputs):

Code: Select all

trendLong= emaFast > emaSlow
trendShort = emaSlow > emaFast
OR

Code: Select all

trend = na
if emaFast > emaSlow
    trend  := "Long"
else if emaSlow > emaFast
    trend := "Short"
???

Or is there any difference?

processingclouds
Pine Script Master
Pine Script Master
Posts: 115
Joined: January 30th, 2022

Re: Efficiency of code

First version is more efficient , as you are assigning bool (true/false) values to the variables. These can than be checked using conditional checks directly and more efficiently used. In second case , you are assigning string values, so you would than be checking string comparisons.

Code: Select all

trendLong= emaFast > emaSlow
trendShort = emaSlow > emaFast

trend = na
if emaFast > emaSlow
    trend  := "Long"
else if emaSlow > emaFast
    trend := "Short"
    
// Example One Check
if (trendLong) 
	// Do Something
else if (trendShort)
	// Do Something

// Example Two Check
if (trend == "Long")
	// Do something
else if (trend == "Short")
	// Do something
    
As you can see in example one , it is directly checking a bool value where as in second example it has to check each character to compare and see if it is a match. Technically in above you will not notice any kind of difference, but bool comparisons are more efficient performance wise too.

Return to “Pine Script Q&A”