faqts : Computers : Programming : Languages : PHP : Common Problems : Tips and Tricks

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

18 of 25 people (72%) answered Yes
Recently 6 of 8 people (75%) answered Yes

Entry

What is the most efficient way to implement counters?

Jun 10th, 1999 07:00
Nathan Wallace, M.Brands, Sander Pilon


You can store the value of the counter in the targetpart of a symlink
(use readlink and symlink commands). This is a lot faster than using a
file (for several reasons). It only works on UNIX machines though.

What ever you try, file or symlink, you'll have to make sure there's
only one process changing a counter at a time. In other words, lock the
damn thing.

You do have to use some kind of locking. You need to do at least four
things:
 1 - read the targetpart of the symlink
 2 - increase the number
 3 - delete the symlink
 4 - create a new one

Your PHP can be interrupted between (maybe even in) any of these
actions. The process of creating or reading a symlink is atomic, but
changing the target isn't.

If you want to use a database then the new MySQL (2.23.x, yet
unreleased) has a 'HEAP' table - which is completely in memory, it
should be perfect for counters. (Sync it with a 'normal' on disk table
every XXX hits.)