Performance issue, when generating around 800~ options from jSon object via javascript.
Any suggestion, what to change or use, to remove those freezes, when new list is generated?
Using jQuery.
function build_towns(selected,selected_country,selected_regions,selected_rajons)
{
tow_box.html(tow_box_empty);
var towns_priority = '';
var towns_options = '';
for(i=0;i < towns.length;i++)
{
if(selected_country > 0) {var find_similar = selected_country;var compare_to = towns[i].country_id;}
else if(selected_regions > 0) {var find_similar = selected_regions;var compare_to = towns[i].region_id;}
else if(selected_rajons > 0) {var find_similar = selected_rajons;var compare_to = towns[i].rajons_id;}
else {var find_similar = 1;var compare_to = 1;} // always will be equal, so it's the same as VIEW ALL
if(find_similar == compare_to)
{
if(towns[i].priority > 0)
{
if(towns[i].town_id == selected) {towns_priority += "<option value='" + towns[i].town_id + "' country='" + towns[i].country_id + "' region='" + towns[i].region_id + "' rajons='" + towns[i].rajons_id + "' selected>" + towns[i].town + "</option>";}
else {towns_priority += "<option value='" + towns[i].town_id + "' country='" + towns[i].country_id + "' region='" + towns[i].region_id + "' rajons='" + towns[i].rajons_id + "'>" + towns[i].town + "</option>";}
}
else
{
if(towns[i].town_id == selected) {towns_options += "<option value='" + towns[i].town_id + "' country='" + towns[i].country_id + "' region='" + towns[i].region_id + "' rajons='" + towns[i].rajons_id + "' selected>" + towns[i].town + "</option>";}
else {towns_options += "<option value='" + towns[i].town_id + "' country='" + towns[i].country_id + "' region='" + towns[i].region_id + "' rajons='" + towns[i].rajons_id + "'>" + towns[i].town + "</option>";}
}
}
}
if(towns_priority.length > 0) {return "<option value='0'>----------------</option>" + towns_priority + "<option value='0'>----------------</option>" + towns_options;}
else {return towns_options;}
}
Thanks.
One problem you have there is that you keep concatenating strings. This is generally wrong in all languages. In JavaScript, this will be faster:
That said, you should profile your code and see what is the slowest part. 800 DOM elements don’t sound like much, but it could make some browsers hang. It is possible you’ll have to live with it.
By the way, usability-wise, 800 is too much for a combo. I’d go with auto-complete. You’re using AJAX anyway here, so auto-complete is even the faster option…