[Tutor] global variables/constants versus volatile variables/constants
Albert-Jan Roskam
fomcl at yahoo.com
Fri Jun 13 14:10:28 CEST 2014
----- Original Message -----
> From: Steven D'Aprano <steve at pearwood.info>
> To: tutor at python.org
> Cc:
> Sent: Friday, June 13, 2014 1:45 PM
> Subject: Re: [Tutor] global variables/constants versus volatile variables/constants
>
> On Fri, Jun 13, 2014 at 12:51:25PM +0530, diliup gabadamudalige wrote:
>> Hi All!
>> Hope everyone is well.
>>
>> In my code there are many dictionaries and lists which are used in various
>> functions. Is it better/pythonic/efficient to have these inside the
>> function itself or declared at the beginning of the program in which case
>> they will be global? They are all read only. I understand that global
>> constants and variable have memory allocated to them but when declared
>> inside a function are created on the fly, used and discarded. Please
>> enlighten me further on this and correct me if i'm wrong.
>
> A good question.
>
> Depending on the size of these dictionaries and lists, worrying about
> efficiency here may be premature optimization. As they say:
>
>
> "We should forget about small efficiencies, say about 97% of
> the time: premature optimization is the root of all evil."
> -- Donald Knuth
The other day I used collections.namedtuple and I re-initialized Record (see below) with every function*) call. Bad idea!
It looks nicer because I did not need a global (and globals are baaad, mkay?), but it was *much* slower. I processed a log of a few million lines, I think.
# bad --> time-consuming
import collections
def do_something_with(raw_record):
Record = collections.namedtuple("_", " ".join("v%%03d" % i for i in range(100)))
return Record(*raw_record.split())
# better --> even though it uses a global variable
import collections
Record = collections.namedtuple("_", " ".join("v%%03d" % i for i in range(100)))
def do_something_with(raw_record):
return Record(*raw_record.split())
*) the function contained more code, of course!
Albert-Jan
More information about the Tutor
mailing list