cairo-book icon indicating copy to clipboard operation
cairo-book copied to clipboard

Advanced Cairo: gas optimisation for break conditions of loops

Open feltroidprime opened this issue 1 year ago • 5 comments

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;
    }
}

feltroidprime avatar Dec 05 '23 16:12 feltroidprime

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.

enitrat avatar Dec 05 '23 16:12 enitrat

lol, i just noticed this is an infinite loop.

copy pasted the wrong example. Edited.

feltroidprime avatar Dec 05 '23 16:12 feltroidprime

@feltroidprime do you want to write a section about gas golfing in Cairo (1)?

enitrat avatar Dec 05 '23 16:12 enitrat

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

enitrat avatar Dec 05 '23 16:12 enitrat

Will be for chapter advanced cairo, probably gas optimizations

enitrat avatar Feb 06 '24 14:02 enitrat

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

TAdev0 avatar Jun 25 '24 11:06 TAdev0