Presumably an import is no faster or slower than opening a file?

Paul McGuire ptmcg at austin.rr.com
Sun Apr 6 12:25:35 EDT 2008


On Apr 6, 8:41 am, tinn... at isbd.co.uk wrote:
> I'm trying to minimise the overheads of a small Python utility, I'm
> not really too fussed about how fast it is but I would like to
> minimise its loading effect on the system as it could be called lots
> of times (and, no, I don't think there's an easy way of keeping it
> running and using the same copy repeatedly).
>
> It needs a configuration file of some sort which I want to keep
> separate from the code, is there thus anything to choose between a
> configuration file that I read after:-
>
>     f = open("configFile", 'r')
>
> ... and importing a configuration written as python dictionaries or
> whatever:-
>
>     import myConfig
>
> --
> Chris Green

Chris -

The question is less an issue of the file overhead (both must open a
file, read its contents, and then close it) than what is done with the
file contents afterwards.

A config file containing .INI-style or whatever content will need to
be parsed into Python data/objects, and likely use Python code to do
so.  An import will use the Python compiler itself, using optimized
compiled C code to do the parsing and data/object construction.  But I
think you would only see the distinction in a config file of
substantial size or complexity.  If you think this will make a
substantial difference in performance, then code up a test case and
time it.

In general, I'd say that splitting performance hairs to tip a design
choice one way or another is a misguided premature optimization.

-- Paul



More information about the Python-list mailing list