Grokking Algorithms



Yüklə 348,95 Kb.
Pdf görüntüsü
səhifə47/122
tarix05.12.2023
ölçüsü348,95 Kb.
#173611
1   ...   43   44   45   46   47   48   49   50   ...   122
grokking-algorithms-illustrated-programmers-curious

Chapter 5
 
 
I
 
 
Hash tables
a couple of minutes. Now, suppose she always asked, “How far is the 
Moon?” Pretty soon, you’d memorize that the Moon is 238,900 miles 
away. You wouldn’t have to look it up on Google … you’d just remember 
and answer. This is how caching works: websites remember the data 
instead of recalculating it.
If you’re logged in to Facebook, all the content you see is tailored just 
for you. Each time you go to facebook.com, its servers have to think 
about what content you’re interested in. But if you’re not logged in to 
Facebook, you see the login page. Everyone sees the same login page. 
Facebook is asked the same thing over and over: “Give me the home 
page when I’m logged out.” So it stops making the server do work to 
figure out what the home page looks like. Instead, it memorizes what 
the home page looks like and sends it to you.
This is called 
caching
. It has two advantages:
• You get the web page a lot faster, just like when you memorized the 
distance from Earth to the Moon. The next time your niece asks you
you won’t have to Google it. You can answer instantly.
• Facebook has to do less work.
Caching is a common way to make things faster. All big websites use 
caching. And that data is cached in a hash! 


85
Use cases
Facebook isn’t just caching the home page. It’s also caching the About 
page, the Contact page, the Terms and Conditions page, and a lot more. 
So it needs a mapping from page URL to page data.
When you visit a page on Facebook, it first checks whether the page is 
stored in the hash.
Here it is in code:
cache = {}
def get_page(url):
if cache.get(url):
return cache[url] 

Yüklə 348,95 Kb.

Dostları ilə paylaş:
1   ...   43   44   45   46   47   48   49   50   ...   122




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin