一个PHP的小技巧
如何实现一个耗时的函数或者类的方法多次调用时, 第一次进行运算, 以后再调用这个函数时, 直接返回结果?
<?php
class MyDate
{
public static function getCurrentDate()
{
static $current_date = '';
if (!$current_date) {
echo 'only run one time';
usleep(200000);
$current_date = date('Y-m-d H:i:s');
}
return $current_date;
}
public static function getCurrentDate2()
{
usleep(200000);
echo 'run everytime';
return date('Y-m-d H:i:s');
}
}
$start = microtime(true);
$i = 5;
while ($i--) {
MyDate::getCurrentDate();
}
echo microtime(true) - $start; //200ms
$start = microtime(true);
$i = 5;
while ($i--) {
MyDate::getCurrentDate2();
}
echo microtime(true) - $start; //1s一个小技巧能提高不少性能
相关推荐
Crazyshark 2020-11-13
klarclm 2020-06-13
songshijiazuaa 2020-06-13
spinachcqb 2020-05-29
olyqcool 2020-05-29
austindev 2020-05-08
amberom 2020-03-08
Nicolase 2020-02-25
jkzyx 2020-02-23
xuelang0 2020-01-24
Nicolase 2019-11-06
liuwendao 2016-11-04
CsdnGame 2016-05-11
怕什么真理无穷 2019-06-27
怕什么真理无穷 2019-06-26
jingxiao 2019-06-26
快雪时晴天 2010-04-24
ahxxx 2019-06-21