If I understand your query correctly, you can gain an immediate efficiency by calling the Crossrider db using appAPI.db.getList to obtain an array of all the database items (instead of calling the database for each id), and then process the ids against them.
I'm happy to look into other ways of improving the efficiency of your algorithm if you provide the extension id.