Skip to content

Commit

Permalink
Optimized Time::i18nFormat() for when it is run multiple times
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Aug 10, 2014
1 parent 084651d commit 94bda33
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions src/Utility/Time.php
Expand Up @@ -99,6 +99,13 @@ class Time extends Carbon implements JsonSerializable {
*/
public static $wordEnd = '+1 month';

/**
* In-memory cache of date formatters
*
* @var array
*/
protected static $_formatters = [];

/**
* {@inheritDoc}
*/
Expand Down Expand Up @@ -554,16 +561,20 @@ protected function _formatObject($date, $format, $locale) {
}

$timezone = $date->getTimezone()->getName();
$formatter = datefmt_create(
$locale,
$dateFormat,
$timeFormat,
$timezone === '+00:00' ? 'UTC' : $timezone,
$calendar,
$pattern
);

return $formatter->format($date);
$key = "{$locale}.{$dateFormat}.{$timeFormat}.{$timezone}.{$calendar}.{$pattern}";

if (!isset(static::$_formatters[$key])) {
static::$_formatters[$key] = datefmt_create(
$locale,
$dateFormat,
$timeFormat,
$timezone === '+00:00' ? 'UTC' : $timezone,
$calendar,
$pattern
);
}

return static::$_formatters[$key]->format($date);
}

/**
Expand Down

0 comments on commit 94bda33

Please sign in to comment.