generator expressions: performance anomaly?

Stephen Thorne stephen.thorne at gmail.com
Tue Jan 18 08:52:24 EST 2005


On Tue, 18 Jan 2005 07:12:18 -0500, Steve Holden <steve at holdenweb.com> wrote:
> Since it doesn't yet optimize 2+5 to a constant-folded 7 you should
> realize that you are suggesting a large increase in the compiler's
> analytical powers.

As in interesting aside to this, you might be interested to know that
PHP has constant folding, allowing you to do things like
$foo = 7+9; and have it generate bytecode that is "let 'foo' equal 16"
or somesuch.

PHP achieves this by having a subset of expression parsing available
only for situations where a folded constant is allowed.

i.e.
class Foo {
  var $bar = 1+4; /* this constant is folded */
}

static_scalar: /* compile-time evaluated scalars */
        common_scalar     |   T_STRING     |   '+' static_scalar     |
  '-' static_scalar     |   T_ARRAY '(' static_array_pair_list ')'
;
common_scalar:
/* all numbers, strings-not-containing-variable-interpolation and a
few hacks like __FILE__ and __LINE__ */
;

As you can see from the grammar, there are any number of ways this can break.

i.e.
Parse Error, * isn't allowed:
class Foo { var $bar = 60*60*24; }

Parse Error, neither is anything except + and -:
class Foo { var $bar = 256 & 18; }

Parse Error, and definately not variables:
$baz = 12;
class Foo { var $bar = $baz*2; }

I compute 60*60*24 every time around the loop:
foreach ($myarray as $value) { $x = 60*60*24*$value; }

Thankful, Former PHP Programmer,
Stephen Thorne.



More information about the Python-list mailing list