Make WordPress Core

Opened 23 hours ago

Last modified 23 hours ago

#66141 assigned enhancement

Hoist loop-invariant `current_time()` calls out of `get_calendar()`

Reported by: mukesh27 Owned by: mukesh27
Priority: normal Milestone: 7.2
Component: General Version:
Severity: normal Keywords: has-patch
Cc: Focuses: performance

Description

get_calendar() calls current_time() inside the day loop to decide which cell gets id="today":

for ( $day = 1; $day <= $daysinmonth; ++$day ) {
        ...
        if ( (int) current_time( 'j' ) === $day
                && (int) current_time( 'm' ) === $thismonth
                && (int) current_time( 'Y' ) === $thisyear
        ) {

The current date does not change while the loop runs, so all three reads are loop-invariant. Each current_time() call with a non-timestamp type goes through wp_timezone() -> wp_timezone_string(), which reads the timezone_string option (and gmt_offset when that is empty), and then constructs a fresh DateTimeZone and DateTime. Because the option lookups run the option_* / pre_option_* filters on every call, the work is not free even with a warm alloptions cache.

For a 31-day month that is 31 current_time( 'j' ) calls, plus two more on the day that matches, i.e. ~33 timezone/DateTime constructions and ~33+ filtered option reads per calendar render. The else branch that determines the current month also calls current_time() twice more:

} else {
        $thisyear  = (int) current_time( 'Y' );
        $thismonth = (int) current_time( 'm' );
}

There is a secondary correctness benefit. Reading the day, month and year as three separate calls means the values can straddle a boundary: if the loop crosses local midnight (or, in the else branch, a new year) between two calls, the pieces describe two different dates and "today" can be highlighted on the wrong cell or on no cell at all. Reading the date once makes the three components consistent by construction.

Change History (2)

#1 @mukesh27
23 hours ago

  • Milestone Awaiting Review7.2
  • Owner set to mukesh27
  • Status newassigned

This ticket was mentioned in PR #13615 on WordPress/wordpress-develop by @mukesh27.


23 hours ago
#2

  • Keywords has-patch added; needs-patch removed

Trac ticket: https://core.trac.wordpress.org/ticket/66141

Use of AI Tools

AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Opus 5
Used for: Drafting the ticket description. Reviewed and verified by me.

Note: See TracTickets for help on using tickets.