Stupid state trick

Occasionally I find myself writing a Perl subroutine that uses a module that no other part of the code needs. This subroutine may be called multiple times, or not at all. At some point I wondered if putting some logic around the require statement would be faster than just calling it every time. require() is idempotent, after all. You could do something like $counter++ or require Foo;, but the variable has to live somewhere outside the subroutine. Not neat.

It occurred to me that, given Perl 5.10 or greater, something like state $dummy = require Foo; might do the trick. I would be willing to bet this is a use of state that was not anticipated when it was designed. But does it actually do what I want, and is what I want worth doing?

The answer to the first question is "yes." A quick script with require overridden proved that the module was in fact loaded, and that require was called only once no matter how many times it was executed.

The answer to the second question is "maybe not." Wrapping my code in the Benchmark module showed that, after the first call, the state implementation ran in a quarter the time of a bare require. But require is actually pretty fast if the module has already been loaded. A billion (American-style, 10**9) iterations of the state trick took 15 seconds on my machine, but then the bare require took only 61 seconds.

Conclusion: the crazy idea of guarding a require with a state variable works, and once the module has actually been loaded significantly reduces the time taken. But unless you are doing seriously large iterations of the code the time saving is probably not worth bothering about.

The script I used is available here.


Nice, you never know when these kind of micro-optmizations might come in handy.

I'd like to see some details about the kind of time that is saved using tricks like this.

Leave a comment

About Tom Wyant

user-pic Fine Perl code for over 0.005 centuries.