Performance: Caching strategies for cost reduction
This affects how quickly data is retrieved and how often expensive API calls or computations happen, reducing load time and cost.
Jump into concepts and practice - no test required
cache = {}
async def get_answer(query):
if query in cache:
return cache[query]
response = await call_expensive_api(query)
cache[query] = response
return responseasync def get_answer(query): response = await call_expensive_api(query) return response
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No caching, repeated API calls | Minimal | Minimal | High due to waiting | [X] Bad |
| In-memory caching of API results | Minimal | Minimal | Low, fast response | [OK] Good |
get_or_set method?get_or_set syntaxcache.get_or_set(key, lambda: expensive_call()) to delay call until needed.cache = InMemoryCache()
result1 = cache.get_or_set('key1', lambda: 'data1')
result2 = cache.get_or_set('key1', lambda: 'data2')
What will be the value of result2?get_or_set behaviorcache = RedisCache()
result = cache.get_or_set('key', expensive_call())
What is the likely cause of the error?