0

In the official Python speed tips wiki, it mentioned the following regarding class.member:

Suppose you can't use map or a list comprehension? You may be stuck with the for loop. The for loop example has another inefficiency. Both newlist.append and word.upper are function references that are reevaluated each time through the loop. The original loop can be replaced with:

upper = str.upper
newlist = []
append = newlist.append
for word in oldlist:
    append(upper(word))

What does "function references that are reevaluated each time" mean? Python re-interprets the function everytime class.member is called?

stevew
  • 674
  • 10
  • 19
  • 4
    See https://stackoverflow.com/a/30379001/476. Each time you access a method on an object, you get a *bound method*. — This might be a very slight optimisation indeed, but one that hardly matters in actuality, and most likely doesn't warrant making the code more complicated. If you require *this* level of performance enhancement, program in C. – deceze Jun 01 '21 at 12:01
  • *"Python re-interprets the function every time `class.member` is called?"* - No, it just checks which object it belongs to every time. The function source itself is only interpreted once. – Tomalak Jun 01 '21 at 12:18
  • FWIW, consider that the language gives no guarantee that ``newlist.append`` gives the same result every time it is accessed. It's trivial to create a type/value for which this expression gives a different result each time it is evaluated. – MisterMiyagi Jun 01 '21 at 12:20
  • Here's a small challenge: Make two versions of the same code. One that uses `newlist.append(str.upper(word))` and one that uses the suggested alternative `append(upper(word))`. Use [a `timit` timer](https://stackoverflow.com/a/25823885/18771) to find out how long each variant takes. Increase the length of the input list until you start to measure a significant difference. – Tomalak Jun 01 '21 at 12:26
  • @MisterMiyagi. `list.append` is not explicitly, but is practically guaranteed to give different results every time it's called. – Mad Physicist Jun 01 '21 at 14:41
  • @MadPhysicist Sure, in practice the many "ifs" needed for ``list.append`` to be consistent are pretty much always true. But it can be helpful to keep in mind that the interpreter cannot assume that to be always true. – MisterMiyagi Jun 01 '21 at 14:50
  • @MadPhysicist @MisterMiyagi can I please clarify why `list.append` isn't guaranteed to give the same result? Is it because the `list` instance is different (if that's what you meant)? – stevew Jun 01 '21 at 23:12
  • @stevew. Calling `append` on the same instance will create a new, different bound method object every time. `k = []; a = k.append; b = k.append;`. `a is b` will be False, though of course both methods behave identically. – Mad Physicist Jun 02 '21 at 00:53

0 Answers0