Find out what's actually slow
Before you optimise anything at all.
This takes <n> seconds and shouldn't: <paste the code or describe the operation> Don't optimise anything yet. 1. How do I measure where the time actually goes? Give me the specific tool or the timing code to add. 2. Given this code, what are the candidates, ordered by how often each turns out to be the real cause? 3. Which single measurement distinguishes between them? I'll come back with numbers. Then we fix the biggest one only.
In server code, check for a query inside a loop before anything else. It's the cause more often than everything else combined.