I believe this is a case of being too paranoid in optimization. Here's some problems:
arris global. You should probably place this somewhere only the widget knows about.
You're clearning the array... by creating another array. You're spawning more objects (in this case, an array) instead of cleaning up. The proper way to clear an array is to set
lengthto 0. If nothing references the items in the array, they'll get GC'ed eventually.
focusoutcan go out of sync. When you focus on the input, you do
getJSON. However, your
autocompletewill run regardless if the request has returned. So that means the array might be empty when autocomplete runs. When you focus out, you cleared your array, so if you focus in again, this happens.
You're making unnecessary AJAX calls. On focus, you're calling AJAX. In the real world, waiting for AJAX is a more painful experience than memory consumption. With proper practice, the GC can and will reclaim memory but you can't reclaim the time you waited for AJAX.
I suggest you do the following instead:
You can limit the returned results to a reasonable length. That way, even if you hit the server with AJAX for each keypress, the return won't take that long.
Cache your results. Have some internal logic which caches returned data into an array (add when non-existent, update if existing). The problem here isn't the size of your cached data. It's the way you're discarding data and retrieving them back again.