[phpa] Re: define vs globals

>
> Hello,
>
> the 2 funtions below accomplish the same:
>
> $test = "hello world";
> define("TEST", "hello world");
>
> function myfunc1()
> {
>   global $test;
>   echo $test;
> }
>
> funtion myfunc2()
> {
>   echo TEST;
> }
>
> I remember from my C-programming days that a define was often better,
> because it was replaced by the value at compile time.

Hi,

Interesting question, although I was asking myself better than what
when I read this. #define isn't really 'better' than anything, and with
modern compilers, using #define isn't necessary with there being
support in the language for achiving the same results performance wise.
That said, PHPA has plenty of #defines in it.

>
> Because PHP compiles a script each time it is requested, I never saw
> this as an issue. But now I was wondering whether this would make a
> difference when using php-accelerator. Since the accelerator stores
the
>  compiled code, I'm wondering if using defines is significantly
faster
> (assuming that I'm using a lot of them, for language files in my
> application) than using global variables? Or does PHP handle defines
> the  same as global variables internally?

Define in PHP is different to the define in CPP (#define isn't a C
compiler construct as such, but is understood by a preprocessor that
processes C source before it's processed by the compiler proper).
Define happens at run time in PHP, and can actually yield reduced
acceleration with PHPA if constants are used as array indices. This is
because of the way support was hacked into PHP post 4.0.6, and where as
a result, PHP actually modifies the compiled code during execution,.
PHPA has to work around the kludge and that incurs a performance
penalty.

In almost all cases, performance shouldn't be the only concern for
production code, and if using defines makes your code more
understandable and maintainable, then it should probably be used.
You're unlikely to notice any substantial performance differences from
using it or not, except possibly in the above mentioned case.

More performance gains are likely from not writing code such as:

for ($i = 0; $i < count($arr); $i++) { }

For some reason the design of PHP doesn't optimise count($arr) to a
dedicated opcode for returning array length, and so incurs a
performance penalty that can be eliminated by assigning the count to a
variable prior to the loop, and testing the variable instead.

But if in doubt, try some performance tests for yourself to determine
the best coding approacb for your system.




------------------------------------------------------------------------
  www.php-accelerator.co.uk           Home of the free PHP Accelerator

To post, send email to phpa@xxxxxxxxxxxxx
To unsubscribe, email phpa-request@xxxxxxxxxxxxx with subject unsubscribe


Other related posts: