Is there a clean way to check a variable inside a loop on the first iteration only or before its execution?

Viewed 453

My code is in Python, but this question goes for any programming language.

Basically, I have a loop that has a structure similar to this:

while True:
    if visual:
        print("Something meaningful")
    function1()
    function2()

The visual variable is determined by the user when he calls the script with CLI arguments, its a boolean. Basically, if set to True, the user gets visual feedback, if False, he doesn't.

The problem is that the loop is going to check that variable on every iteration, slowing down the execution slightly.

I therefore wondered if there is a clean way to avoid having to check if "visual" is True on every iteration, to somehow tell the program to check that variable only on the first iteration, since the variable can't change mid-execution.

I thought of doing something like this :

if visual:       
    while True:
        print("Something meaningful")
        function1()
        function2()
else:
    while True:
        function1()
        function2()

It works, but it doesn't seem like good practice at all.

What is the cleanest way to solve this problem ?

2 Answers

I would begin with grouping the functions from the while loop into a new function. Then before the loop we check if visual is True, if it is then we decorate functions() with a wrapper.

def functions():
    function1()
    function2()

def _visual_decorator(func):
    def _wrapper(*args, **kwargs):
        print("Something meaningful")
        return func(*args, **kwargs)
    return _wrapper

if visual:
    functions = _visual_decorator(functions)

while True:
    functions()

Full working example

You're after a branchless programming approach. You should transform your loop so that it doesn't use the first branching if.
To do that generally depends on the language you're using and the features that it provides.
For example, in Python, you could put two functions in a map and use one of them according to the variable value:

functions = {True: print, False: lambda x: x}
value = False
func = functions[value]
while True:
  func("Something useful")
  function1()
  function2()

This is one way to do it, and it is not the only way. Other languages have their own way to achieve the same thing.
Note that while in Python this might not give much difference, brancheless programming in general could potentially optimize your programs running time, sometimes by orders of magnitude!

Related