1

This is related to performance, I was wondering does nested if-else statement perform faster than jQuesy selectors query or is is the other way around?

if (valid)
{
    // do something
}
else if ($(something).parent().data('somePlugin').options.data1 > 0)
{
    error = 'Must be larger than ' + $(something).parent().data('somePlugin').options.data1;
}
else if ($(something).parent().data('somePlugin').options.data2 < 0)
{
    error = 'Must be larger than ' + $(something).parent().data('somePlugin').options.data2;
}

VS

if (valid)
{
    // do something
}
else 
{
    $plugin = $(something).parent().data('somePlugin');

    if ($plugin.options.data1 > 0)
    {
        error = 'Must be larger than ' + $plugin.options.data1;
    }
    else if ($plugin.options.data2 < 0)
    {
        error = 'Must be larger than ' + $plugin.options.data2;
    }
}
Ewe Seong
  • 67
  • 6
  • It's about caching nodes, and not requery DOM again. `$plugin = $(something).parent().data('somePlugin');` is what you should do. – dfsq Jun 29 '14 at 07:25
  • does jQuery cache the executed query? I always thought $('selector') will cause the jQuery to query again. – Ewe Seong Jun 30 '14 at 07:15
  • thanks, google caching nodes answer a lot of my question. – Ewe Seong Jun 30 '14 at 07:21

0 Answers0