cairo-book
cairo-book copied to clipboard
Advanced Cairo: gas optimisation for break conditions of loops
The example shown in https://book.cairo-lang.org/ch02-05-control-flow.html?highlight=loop#repetition-with-loops
currently demonstrates
fn main() {
let mut i: usize = 0;
loop {
if i > 10 {
break;
}
'again'.print();
i += 1;
}
}
as a main example
This doesn't show best practice which is to avoid at all cost comparison operators to break out of loops.
It is much cheaper to compare numbers i == 11
rather than doing i>10
, as internally ">" or "<" does range checks and calls the relevant libfunc, whereas numbers equality costs 2 steps, and zero checks ==0
or !=0
cost 1 step.
The best case, if possible, is to start from the latest index (10), decrement i, and check i==0.
fn main() {
let mut i: usize = 10;
loop {
if i == 0 {
'again'.print();
break;
}
'again'.print();
i -= 1;
}
}
lol, i just noticed this is an infinite loop.
Indeed it's better to use strict equality checks - provided that i is increased by incrementation of ones.
lol, i just noticed this is an infinite loop.
copy pasted the wrong example. Edited.
@feltroidprime do you want to write a section about gas golfing in Cairo (1)?
whereas numbers equality costs 2 steps, and zero checks ==0 or !=0 cost 1 step.
Honestly, given all the overhead that the sierra abstractions imposes, I don't even think it's worth mentioning apart from in deep step optimisation chapters
Will be for chapter advanced cairo, probably gas optimizations
closing as we will not add a dedicated chapter for gas optimisation. I'll push a PR to add in control flow section informations about avoiding range check builtin usage with equality check