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

Optimization: Short circuit evaluation #215

Open
CJHarmath opened this issue Jul 25, 2023 · 0 comments
Open

Optimization: Short circuit evaluation #215

CJHarmath opened this issue Jul 25, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@CJHarmath
Copy link

Overview

While testing rocketry with minutely and a cond function with logging, I've noticed that the cond function keeps getting called every 100ms even when the timer is false.
i.e.: there is no short-circuit evaluation which is common with logic operators.
https://en.wikipedia.org/wiki/Short-circuit_evaluation

Below is a sample using env variables based feature flag just as a demonstration

@app.cond()
def is_feature_enabled():
  print("condition check")
  return os.getenv("MY_FEATURE_ENABLED", "true").lower() in ("true", "1", "y", "yes")

@app.task(minutely & is_feature_enabled)
async def my_task():
  print("my task is running")

Actual behavior

This will be printing "condition check" even 100ms or the configured cycle_sleep

Expected behavior

only check the condition once a minute, removing unnecessary CPU cycles spent on evaluation calls in the cond function.
the result of the cond function does not matter as the logical AND operation will always be FALSE if the left side is FALSE.

Proposal

One solution could be to add the short-circuit logic to the and operator override in the base class as below:

    def __and__(self, other):
        # self & other
        # bitwise and
        # using & operator
        # short-circuit if self is false to avoid spinning our wheels evaluating other
        if not self: 
          return False
        return All(self, other)

I've only looked at the code briefly, so there might be other optimization areas.

Note

Great little package, thanks for sharing!

@CJHarmath CJHarmath added the enhancement New feature or request label Jul 25, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant