Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement short circuit evaluation for AND, OR #22

Open
nippur72 opened this issue Mar 13, 2019 · 3 comments
Open

Implement short circuit evaluation for AND, OR #22

nippur72 opened this issue Mar 13, 2019 · 3 comments

Comments

@nippur72
Copy link
Contributor

IF cond1 AND cond2 THEN ...
IF cond3 OR cond4 THEN ...

If cond1 is false there is no need to evaluate cond2, it will be always false. Similarly if cond3 is true no need to evaluate cond4 as it will be always true.

That could provide some speed increase. The only caution is that cond2 and cond4 should not contain call to impure functions (functions that have side effects) but to my knowledge almost all BASIC V2 functions are pure (except RND and FN?).

@EgonOlsen71
Copy link
Owner

I already thought about this some time ago, but for some reason (that I don't remember ATM), it wasn't that easy to implement in this context. So I decided against it. When I find the time, I might take a look at it again...

@EgonOlsen71
Copy link
Owner

EgonOlsen71 commented Mar 14, 2019

Thinking about it, I remember my actual problem with it. This logic applies to AND and OR when they are boolean operators. But in BASIC V2, what they actually are, are bitwise AND and OR operators. That means, that

if x=5 and y=12 then...

can easily be optimized to

if x=5 then if y=12 then...

(which is the same as you've suggested, but in BASIC source code)

but something like

if a and 8 then...

can't. Or more complex:

if (b>2)*-8 and 2*b then ...

can't either. Right now, I'm lacking a clever idea how to separate these cases correctly without going overboard with it...hmm...

@nippur72
Copy link
Contributor Author

thinking about it... when evaluating the AST, your expression nodes might also include a isBoolean property that bubbles up to the root, e.g.

b<2 => return { ..., isBoolean: true }
b * 4  => return { ..., isBoolean: false }
expr1 AND expr2 => return { ..., isBoolean: expr1.isBoolean AND expr2.isBoolean }
expr1 OR expr2 => return { ..., isBoolean: expr1.isBoolean AND expr2.isBoolean }

then you can check the root node of your IF expression and if it's isBoolean you can apply short circuit optimization. Something like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants