Search code examples
aemsightlyhtl

What is the difference between sightly var and calling of sling model's getter?


What is the difference between:

<div data-sly-test.backgroundVideo="${hero.backgroundVideo}" >
    Background video URL:
        <a href="${backgroundVideo}.html" target="_blank">
            ${backgroundVideo}
        </a>
</div>

and:

<div data-sly-test="${hero.backgroundVideo}" >
    Background video URL:
        <a href="${hero.backgroundVideo}.html" target="_blank">
            ${hero.backgroundVideo}
        </a>
</div>

What solution is more effective? Usage of sightly variable or, calling of getter?


Solution

  • Sightly, just like any other programming language of similar domain, does not force any requirements on variable usage. A simple comparison would be to convert the code into equivalent Java routine and see the optimisation and performance effect (in theory).

    For the sake of simplicity, let's make your POJO class as below:

    class Hero {
    
        public string getBackgroundVideo() {
            //Some model logic
        }
    
    }
    

    Now, consider the first code snippet:

    <div data-sly-test.backgroundVideo="${hero.backgroundVideo}" >
         Background video URL:
            <a href="${backgroundVideo}.html" target="_blank">
            ${backgroundVideo}
            </a>
    </div>
    

    This will only execute the getBackgroundVideo() once and store it in a variable for reuse.

    Alternatively, for the second code snippet:

    <div data-sly-test="${hero.backgroundVideo}" >
        Background video URL:
        <a href="${hero.backgroundVideo}.html" target="_blank">
            ${hero.backgroundVideo}
        </a>
    </div>
    

    getBackgroundVideo() will be executed 3 times.

    So, on the surface this may look like a 1:3 difference in execution and look really costly specially if there is a complex code logic involved in the getBackgroundVideo() function. This is true and you should avoid this approach by trying to cache the output of complex functions as variables.

    However, taking an alternate view on the problem, this also boils down to how well your POJO class is written. So, lets revisit your Hero class:

    class Hero {
        private string backgroundVideo;
    
        public void init() {
             this.backgroundVide = "some value on business logic";
        }
    
        public string getBackgroundVideo() {
            return this.backgroundVideo;
        }
    
    }
    

    If your Hero POJO class is implemented as above, the getBackgroundVideo() just boils down to a simple getter which returns a string value without complex calculations. Of course, there is the overhead of a function call as compared to a local HTL variable but this will be minimal and probably not noticeable.

    To summarise the real effect can only be measured by the POJO implementation but HTL variable approach will almost always give you the caching benefit.