Skip to content

Optimization: Short circuit evaluation #215

@CJHarmath

Description

@CJHarmath

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions