mardi 12 janvier 2021

Why don't PHP developers cache their methods?

I'm hoping this question isn't too opinionated for StackOverflow, it seems like there's a correct answer here that I just can't see.

I've seen a few other languages do this, but PHP is the one I'm looking at now. This question stems from me looking at the Magento 2 source code:

<?php
class Image extends AbstractHelper implements ArgumentInterface
{

    // ...

    protected function setImageProperties()
    {
        $this->_getModel()->setDestinationSubdir($this->getType());
        $this->_getModel()->setWidth($this->getWidth());
        $this->_getModel()->setHeight($this->getHeight());

        // Set 'keep frame' flag
        $frame = $this->getFrame();
        $this->_getModel()->setKeepFrame($frame);

        // Set 'constrain only' flag
        $constrain = $this->getAttribute('constrain');
        if (null !== $constrain) {
            $this->_getModel()->setConstrainOnly($constrain);
        }

        // Set 'keep aspect ratio' flag
        $aspectRatio = $this->getAttribute('aspect_ratio');
        if (null !== $aspectRatio) {
            $this->_getModel()->setKeepAspectRatio($aspectRatio);
        }

        // Set 'transparency' flag
        $transparency = $this->getAttribute('transparency');
        if (null !== $transparency) {
            $this->_getModel()->setKeepTransparency($transparency);
        }

        // Set background color
        $background = $this->getAttribute('background');
        if (null !== $background) {
            $this->_getModel()->setBackgroundColor($background);
        }

        return $this;
    }

(Taken from github)

Again and again, you see $this->_getModel(). I'd have thought it would be more efficient to store the results of that method in a variable and then call it as needed:

<?php
class Image extends AbstractHelper implements ArgumentInterface
{

    // ...

    protected function setImageProperties()
    {
        $model = $this->_getModel();
    
        $model->setDestinationSubdir($this->getType());
        $model->setWidth($this->getWidth());
        $model->setHeight($this->getHeight());

        // ...
    }

And yet, I rarely see server-side programmers do this. Is there a reason why they don't? Is it considered more readable? Does the compiler abstract away the overhead so the two options are as efficient as each other (or even more efficient since there's no variable assignment)?

Aucun commentaire:

Enregistrer un commentaire