I have the following code:
var select_ids = [];
// syntax.filter.select_list is ["elem1", "elem2"]
for (var o = 0; o < syntax.filter.select_list.length; o += 1) {
element = syntax.filter.select_list[o];
if (priv.getPositionInArray(element,select_ids) === null ) {
// this line hangs up the browser
select_ids.unshift(element);
}
}
I don’t understand why push() or unshift() into an empty array when looping two iterations hangs up the browser for 3-4sec.
If I leave away this line:
select_ids.unshift(element);
the script runs instantly, so
Question:
why could push/unshift to an empty array produce such a delay? FYI, this is inside another loop with 3 iterations. For every parent loop I’m resetting select_ids to an empty object to fill.
Thanks!
EDIT:
And I’m doing the if-clause to make sure I don’t add doubles to the array.
EDIT: (full code)
priv.findBestIndexForQuery = function (indices, syntax) {
var i, j, k, l, m, n, p, o, element,
search_ids = [], select_ids = [], use_index = [],
index, query_param, search_param,
// need to parse into object
current_query = jIO.ComplexQueries.parse(syntax.query);
// loop indices
for (i = 0; i < priv.indices.length; i += 1) {
index = {};
index.reference = priv.indices[i];
index.reference_size = index.reference.fields.length;
// rebuild for iteration
if (current_query.query_list === undefined) {
search_ids.push(current_query.id);
} else {
for (j = 0; j < current_query.query_list.length; j += 1) {
if (priv.getPositionInArray(current_query.query_list[j].id,
search_ids) === null ) {
search_ids.push(current_query.query_list[j].id);
}
}
}
for (o = 0; o < syntax.filter.select_list.length; o += 1) {
element = syntax.filter.select_list[o];
if (priv.getPositionInArray(element,select_ids) === null ) {
// line causing problems
select_ids.unshift(element);
}
}
// there is a lot more, but I'm hanging on the line above
}
EDIT (getPostionInArray)
priv.getPositionInArray = function (element, array) {
var i;
for (i = 0; i < array.length; i += 1) {
if (array[i] === element) {
return i;
}
}
return null;
};
As requested by the OP, the issue is, indeed
unshift: there have been bugs with this function (its context is ad-hoc) in the past, and this bug report is still marked as NEW.As for your
getPositionInArrayfunction, why don’t you use the standardindexOfmethod? Most browsers support it, and for those that don’t you can always add this to your script:Or, if you want this method to return
null, instead of-1in all browsers:Just a side-note, some prototype fun 🙂