Demo code that USES the cached APC more efficiently than Memcached on the same server

  • 2020-03-31 20:18:35
  • OfStack


<?php 
$memcachehost = 'localhost'; 
$memcacheport = '11211'; 
function microtime_float(){ 
list($usec, $sec) = explode(" ", microtime()); 
return ((float)$usec + (float)$sec); 
} 
function runtime($t1){ 
return number_format((microtime_float() - $t1)*1000, 4).'ms'; 
} 
$starttime = microtime_float(); 
$cache_time = '30'; 
echo "init=====".runtime($starttime).'<br>'; 

$sql = "SELECT * FROM hx WHERE id = 10006"; 
$mem_sql_key = md5($sql); 

$t1 = microtime_float(); 
echo "APC_read====="; 
$arrs = apc_fetch($mem_sql_key); 
echo runtime($t1).'<br>'; 

$t1 = microtime_float(); 
apc_store($mem_sql_key.'_test', $arrs, $cache_time); 
echo "APC_write====="; 
echo runtime($t1).'<br>'; 

$t1 = microtime_float(); 
$mem = new Memcache; 
$mem->connect($memcachehost, $memcacheport); 
echo "MEM_connet=====".runtime($t1).'<br>'; 

$t1 = microtime_float(); 
$arrs = $mem->get($mem_sql_key); 
echo "MEM_read====="; 
echo runtime($t1).'<br>'; 
$t1 = microtime_float(); 
$mem->set($mem_sql_key.'_test',$arrs,0,$cache_time); 
echo "MEM_write====="; 
echo runtime($t1).'<br>'; 
?>

The result of this SQL is cached in both apc and memcached in advance, and the read/write speed is tested.
Results on native Windows:
Init = = = = = 0.0341 ms
APC_read = = = = = 0.0439 ms
APC_write = = = = = 0.0920 ms
MEM_connet = = = = = 11.0571 ms
MEM_read = = = = = 0.2630 ms
MEM_write = = = = = 0.2270 ms

Results on Linux on server:
Init = = = = = 0.0131 ms
APC_read = = = = = 0.0520 ms
APC_write = = = = = 0.0489 ms
MEM_connet = = = = = 0.0501 ms
MEM_read = = = = = 0.1030 ms
MEM_write = = = = = 0.0801 ms

Of course, repeated refreshes will have different values, but this is just a more average value.
Win does not have any reference, mainly see the results on Linux.
Apc is about twice as fast as memcached before connent time. If you add memcache_connect, it's twice as fast.
APC can implement both the opcode cache for PHP files and the user cache, which is a good thing.

So if all the functionality can be done on a single server when the site is small, then APC should be the preferred caching solution, regardless of memcached. However, if you consider that this time difference in performance is negligible given the growing size of your site, you should deploy memcached.
Also, use memcached across servers, preferably using an Intranet. Otherwise, affected by routing, memcached often times the connection times out (over 100ms) and generates twice as much broadband traffic out of thin air.

Related articles: