Search code examples
opcache

Do static arrays get stored in opcache?


Say I have a rather large associative array of 100k elements like so:

$resources = array(
'stone'=>'current_stone.gif',
'stick'=>'uglystick.jpg',
...
);

Stored in a file called resources.php and it will never change at runtime.

I would like to have this data in Zend opcache so as to share it across all processes (saving memory) and possibly speed up the lookup speed.

My current assumption is that, in this form, this array will not get stored in opcache as it's not defined as a static structure anywhere.

How would I go about making sure this data gets into opcache?


Solution

  • No you can't store variables in OPcache, but statics in classes work:

    class Resource {
        static $image = [
            'stone'=>'current_stone.gif',
            'stick'=>'uglystick.jpg',
            ...
        ];
    }
    ...
    echo Resource::$image['stone'], "\n";
    

    This saves all of the opcodes initialising the arrays, but OPcache will still deep copy the version of Resource::$image in the compiled script in SMA into the corresponding class static property in the process space, so you will still have a copy of the HashTable in each of the active processes which are using Resource -- though the strings themselves will be interned and hence shared across all active php requests which are using this class.

    If you are using a class autoloader, to load your classes, then you don't even need to do anything other than refer to Resoure::$image... and the autoloader will do the mapping for you.