Skip to main content

Performance Optimization 🚀

Memory Management

Efficient Variable Usage

//@version=5
indicator("Memory Optimization")

// BAD: Creating new arrays every bar
inefficientMethod() =>
data = array.new_float(0) // Creates new array each call
array.push(data, close)
array.sum(data)

// GOOD: Reusing arrays with 'var'
var float[] efficientData = array.new_float(0)
efficientMethod() =>
if array.size(efficientData) > 100
array.shift(efficientData)
array.push(efficientData, close)
array.sum(efficientData)

Memory Cleanup

//@version=5
indicator("Memory Cleanup")

// Implement circular buffer
var int maxSize = 100
var float[] buffer = array.new_float(maxSize, 0.0)
var int currentIndex = 0

// Efficient data storage
storeValue(value) =>
array.set(buffer, currentIndex, value)
currentIndex := (currentIndex + 1) % maxSize

Calculation Optimization

Caching Results

//@version=5
indicator("Calculation Caching")

// Cache expensive calculations
var float[] smaCache = array.new_float(0)
var int smaPeriod = 20

getCachedSMA() =>
if barstate.isfirst
array.push(smaCache, ta.sma(close, smaPeriod))
else if barstate.isnew
prevSMA = array.get(smaCache, array.size(smaCache) - 1)
newSMA = (prevSMA * (smaPeriod - 1) + close) / smaPeriod
array.push(smaCache, newSMA)
array.get(smaCache, array.size(smaCache) - 1)

Reducing Recalculations

//@version=5
indicator("Optimize Calculations")

// BAD: Recalculating every bar
inefficientCalc() =>
sum = 0.0
for i = 0 to 99
sum += close[i]
sum / 100

// GOOD: Rolling calculation
var float rollingSum = 0.0
efficientCalc() =>
if barstate.isfirst
rollingSum := ta.sum(close, 100)
else
rollingSum := rollingSum - close[100] + close
rollingSum / 100

Loop Optimization

Efficient Loops

//@version=5
indicator("Loop Optimization")

// BAD: Nested loops
inefficientSearch(float[] data, float target) =>
found = false
for i = 0 to array.size(data) - 1
for j = i + 1 to array.size(data) - 1
if array.get(data, i) + array.get(data, j) == target
found := true
found

// GOOD: Single pass with hash set
efficientSearch(float[] data, float target) =>
var set = array.new_float(0)
found = false
for value in data
if array.includes(set, target - value)
found := true
break
array.push(set, value)
found

Data Structure Optimization

Efficient Data Structures

//@version=5
indicator("Data Structures")

// Using appropriate data structures
type PricePoint
float price
int volume
int timestamp

// Efficient storage
var PricePoint[] priceHistory = array.new<PricePoint>(0)

// Update efficiently
updateHistory() =>
point = PricePoint.new(close, volume, time)
if array.size(priceHistory) > 100
array.shift(priceHistory)
array.push(priceHistory, point)

Request Optimization

Efficient External Requests

//@version=5
indicator("Request Optimization")

// Cache external data requests
var float[] dataCache = array.new_float(0)
var int lastUpdateTime = 0
var int updateInterval = 1000 // milliseconds

getExternalData(symbol) =>
currentTime = timenow
if currentTime - lastUpdateTime > updateInterval
value = request.security(symbol, timeframe.period, close)
array.push(dataCache, value)
lastUpdateTime := currentTime
if array.size(dataCache) > 100
array.shift(dataCache)
array.get(dataCache, array.size(dataCache) - 1)

Script Size Optimization

Code Organization

//@version=5
indicator("Code Organization")

// Use functions for repeated code
commonCalculation(price, length) =>
sma = ta.sma(price, length)
std = ta.stdev(price, length)
[sma, std]

// Reuse calculations
[sma20, std20] = commonCalculation(close, 20)
[sma50, std50] = commonCalculation(close, 50)

Performance Monitoring

Script Performance Metrics

//@version=5
indicator("Performance Monitor")

// Track calculation time
var int[] calcTimes = array.new_int(0)
startTime = timenow

// Your calculations here
result = ta.sma(close, 200)

// Record performance
endTime = timenow
array.push(calcTimes, endTime - startTime)

// Display metrics
if barstate.islast
avgTime = array.sum(calcTimes) / array.size(calcTimes)
label.new(bar_index, high, "Avg Calc Time: " + str.tostring(avgTime) + "ms")
Optimization Tips
  • Use 'var' for persistent variables
  • Cache expensive calculations
  • Minimize loop iterations
  • Use appropriate data structures
  • Optimize external requests
  • Monitor script performance
Performance Pitfalls

❌ Creating new arrays each bar ❌ Unnecessary recalculations ❌ Inefficient loops ❌ Memory leaks ❌ Excessive external requests

Next Steps

Ready to learn about debugging and testing? Move on to the next chapter! 🚀