0

I have function which search patterns in string. If pattern is found function log it to file, else do nothing.

func find(patterns_list, line) {
    foreach pattern in patterns_list {
        if pattern in line {
            log to file
        }
    }
}

I want to add debug mode to my function. If variable debug is set to true, then function print every pattern while checking.

func find(patterns_list, line, debug) {
    foreach pattern in patterns_list {
        if debug is true {
            print pattern
        }
        if pattern in line {
            log to file
        }
    }
}

How to do this without overhead related to condition (debug is true). This piece of code will be slowing function every time.

I know, I can clone function and check condition before running: find() -> normal mode find_debug() -> debug mode

But how to do it without above solution ?

  • 1
    Checking if a boolean variable is true or not is rarely something you need to optimize. Anything you'll do other than writing two functions is likely to perform worse. You can pass a debug function that prints something, and you can pass an empty function if it is not in debug mode, but that'll add a function call overhead, which is worse. – Burak Serdar Aug 22 '19 at 13:29
  • Related: https://dave.cheney.net/2014/09/28/using-build-to-switch-between-debug-and-release – Jonathan Hall Aug 22 '19 at 13:55

0 Answers0