jqueryformsperformancequery-performanceserializearray

JQuery: serializeArray() performance


I've found two different ways to find data entered into a form and am not sure which one to use. I will be working with a fairly big form, so performance is important. The first option uses .serializeArray() and the second one uses .find().val()

Option 1:

var values = {};

$.each($growDetailsForm.serializeArray(), function (i, field) {
    values[field.name] = field.value;
});
var getValue = function (valueName) {
    return values[valueName];
};

var first = getValue("first-name");
var first = getValue("last-name");
...

Option 2:

var $form = $('form');
var $first = $form.find('.first-name').val();
var $last = $form.find('.last-name').val();
...

Does anyone know which option is faster? I'm assuming option 1 is faster, as I believe it grabs all the values at once and puts them into an array, giving you a smaller object to search through. Option 2 searches the entire DOM each time I look for a certain value, which makes me think it is slower. I'm not an expert however, so I'm not real confident. It may not make much of a difference if I'm searching for only two values, but I will be searching for many more than that. Any insight is appreciated.


Solution

  • Unless your form is huge (read way too big!) it won't make any appreciable difference, but if you want to see for yourself you could find out here.

    I would favour readability of code for maintenance later, so the 2nd method seems better to me, though you can simplify that even further to $('.first-name').val()