Can this JavaScript be optimized?

This JS will be executed on pages with a lot of fields. Can you improve the speed of this code anyway? If so, can you explain what you found?

var _TextInputs = null;
function GetTextInputs()
{
    if (_TextInputs == null)
    {
        _TextInputs = jq('input[type=text]');
    }

    return _TextInputs;
}

var _Spans = null;
function GetSpans()
{
    if (_Spans == null)
    {
        _Spans = jq('span');
    }

    return _Spans;
}


function UpdateRate(ratefield, name)
{
    GetTextInputs().filter('[' + name + ']').each(function()
    {
        this.value = FormatCurrencyAsString(FormatCurrencyAsFloat(ratefield.value));
        CalculateCharge(name.replace('Rate', ''), jq(this).attr(name));
    });
}

function CalculateCharge(name, activity_id)
{
    var inputs = GetTextInputs();
    var bill_field = inputs.filter('[' + name + 'Bill=' + activity_id + ']');
    var rate_field = inputs.filter('[' + name + 'Rate=' + activity_id + ']');
    var charge_field = GetSpans().filter('[' + name + 'Charge=' + activity_id + ']'); 

    charge_field.text(FormatCurrencyAsString(FormatCurrencyAsFloat(bill_field.val()) * FormatCurrencyAsFloat(rate_field.val())));
}

      

+2


source to share


3 answers


You can:

  • Replace each

    withwhile

  • Replace val()

    with .value

    (should be fine if these fields are text)
  • Accessing elements by class instead of name / type
  • Replace with attr()

    simple property access; for example: this.attr(name)

    this.name



These are all fairly unobtrusive changes that should speed things up, mainly due to the reduction in function calls.

Do not query for elements on every function call if those elements are static (i.e. they do not change during the life cycle of the application). Instead, store them outside of the loop.

+5


source


I can see that you are using attribute filters everywhere, for example:

_TextInputs = jq('input[type=text]');

inputs.filter('[' + name + 'Bill=' + activity_id + ']');

      

Attribute filters are useful, but not particularly "instant" when compared to more direct classes or identifiers. I don't see any markup, so the best I can suggest is that you use more IDs and classes, like this:



jq('input.textInput');

      

instead:

jq('input[type=text]');

      

+4


source


A bit off-topic, but I use and recommend Javascript Rocks . These books contain a TON of amazing JS optimization advice from the creator of Scriptaculous. It also comes with a tool called DOM Monster that helps track performance bottlenecks - a terrific compliment to Firebug as it actually tracks the DOM looking for inefficiency based on DOM heuristics and complexity.

0


source







All Articles