views:

84

answers:

2

Hi,

I wonder if Perl performs common subexpression elimination?

And what kind of optimisations are done?

+1  A: 

No, but I do.

Now, I don't unroll loops by hand, because loops are an easier concept once you're familiar with programming. Because you could be doing anything with a sequence of commands, the loop makes it clear that you're repeating a task.

But CSE is something that makes more efficient code regardless of the implementation of the language. So I do it. It doesn't make the code baroque, and it works in languages where it's not automatically included.

Perl offers compression of syntax so there are often less subexpressions that have to be hand-eliminated.

Axeman
+1  A: 

No, and its not possible to do it either, except in very simple cases.

In order to eliminate common subexpressions, you must know that they haven't changed their values in between. But since so much can happen between two expressions a few lines apart, its almost impossible to tell if the subexpressions are still common.

The only things you would be able to eliminate are expressions that are provably pure, like "7 + 5". But proving that something like a function call is safe to eliminate is not going to happen.

To do this, you need powerful and conservative static analysis, which Perl does not have, and is not likely to gain (in C/C++ you need less powerful stuff because the languages are less dynamic, but you still need something).

Paul Biggar