Improving Performance of the CloudFlare worker code
-
Hi, thanks for the great plugin.
I did a couple of optimizations to your cloudflare worker code and I see a huge improvement in CPU time consumption on my CF stats.
See the screenshot below, where you can see the drop in CPU time consumption after my optimizations have been deployed (about 17:00) .
Below are the optimizations
1- Optimize url_normalize Function
The url_normalize function iterates over THIRD_PARTY_QUERY_PARAMETERS and checks each query parameter in the URL. This can be optimized by directly checking and deleting the parameters from URLSearchParams without regex testing, which is computationally expensive.Modification:
Directly iterate over the search params and check if it’s in your list of third-party parameters to remove. This avoids regex testing for each parameter.
function url_normalize(event) { try { const reqURL = new URL(event?.request?.url); const params = reqURL.searchParams; THIRD_PARTY_QUERY_PARAMETERS.forEach(param => { if (params.has(param)) { params.delete(param); } }); return reqURL; } catch (err) { return { error: true, errorMessage:
URL Handling Error: ${err.message}
, errorStatusCode: 400 }; } }2- Static File Check Optimization
The check for static files iterates over STATIC_FILE_EXTENSIONS for every request, which is not efficient. Instead, you can use a regex pattern to match the file extension directly from the URL.Modification:
Use a regex to test for static file extensions in one go. (this shall replace the current checking block)
const staticFilePattern = /\.(jpg|jpeg|png|gif|svg|webp|avif|tiff|ico|3gp|wmv|avi|asf|asx|mpg|mpeg|webm|ogg|ogv|mp4|mkv|pls|mp3|mid|wav|swf|flv|exe|zip|tar|rar|gz|tgz|bz2|uha|7z|doc|docx|pdf|iso|test|bin|js|json|css|eot|ttf|woff|woff2|webmanifest)$/i; if (staticFilePattern.test(requestPath)) { isStaticFile = true; }
3- Cache Key Optimization
When constructing the cache key, consider normalizing the request URL to ensure that different query parameter orders or minor differences do not result in cache misses.Modification:
Sort query parameters alphabetically before using them as a cache key.
const sortedSearchParams = new URLSearchParams([...requestURL.searchParams].sort()); const normalizedURL =
${requestURL.origin}${requestURL.pathname}?${sortedSearchParams}
; const cacheKey = new Request(normalizedURL, request);
- The topic ‘Improving Performance of the CloudFlare worker code’ is closed to new replies.