hello I have this function in an angular service which works well, but sometimes it takes too long in responser in fact it blocks the user window for a few seconds when for example I search for matches by a few digits (obviously it returns more results), the question is how I could make this procedure faster using what angular provides, or how this function could be improved
municipiosColombia = ['uno','dos','tres']; // hay 994 elementos
getLikeTown(termino:string){
let municipios:any[] = [];
termino = termino.toLowerCase();
for (let municipio of this.municipiosColombia){
let nombre = municipio.toLowerCase();
if (nombre.indexOf(termino) >= 0) {
municipios.push(municipio);
}
}
return municipios;
}
If you want to improve performance, the best thing you can do is use a
for loop
, you are currently using afor of
, this together withfor in
it does not compare withfor loop
, what's more, common filter functions such as theyreduce/filter/map
still have poor performance compared tofor loop
but in what personal are my options when making a filter, in particular the functionfilter
below I show you a code with the use of
filter
and well the code that should have better performance,
for loop
PS:
includes
eindexOf
work the same with the difference thatincludes
it recognizes comparisons withNaN
andundefined
and returns directlytrue
orfalse
. Also consider thatincludes
it is not supported in IEPD2: Regarding your question about whether to use it on
keyup
or in a button, it should bekeyup
for user experience issues unless the execution is really very slow, in that case you would have to look for another solution, such as the button