Skip to content

⚡ Optimize DateFormatter creation in ActivityHeatmapView#65

Closed
debugtheworldbot wants to merge 1 commit intomainfrom
performance-cache-date-formatters-13101833943979519934
Closed

⚡ Optimize DateFormatter creation in ActivityHeatmapView#65
debugtheworldbot wants to merge 1 commit intomainfrom
performance-cache-date-formatters-13101833943979519934

Conversation

@debugtheworldbot
Copy link
Owner

This PR optimizes the ActivityHeatmapView by caching expensive objects like DateFormatter and Calendar that were previously being created repeatedly during the drawing cycle.

💡 What

  • Added lazy private properties to ActivityHeatmapView to store:
    • calendar (Calendar.current)
    • monthFormatter (DateFormatter with "MMM" format)
    • weekdaySymbols (Localized weekday strings)
    • tooltipDateFormatter (DateFormatter with medium date style)
  • Updated recalculateLayout(), drawMonthLabels(), drawWeekdayLabels(), and updateTooltip() to use these cached properties.

🎯 Why

DateFormatter and Calendar instantiation are known to be expensive operations in macOS/iOS. Creating them inside a drawing loop or frequently called UI methods can lead to:

  • Increased CPU usage
  • Frame drops during resizing or animations
  • Unnecessary memory allocations

📊 Measured Improvement

Direct benchmarks could not be performed as the environment does not provide swift or xcodebuild. However, this change follows standard Apple performance optimization guidelines and is a net positive for any AppKit view performing frequent redraws.


PR created automatically by Jules for task 13101833943979519934 started by @debugtheworldbot

- Caches `DateFormatter` for month and tooltip formatting as lazy properties.
- Caches `Calendar.current` to avoid repeated calls to the system property.
- Caches `weekdaySymbols` to avoid re-generating them on every draw call.
- Refactors `recalculateLayout()`, `drawMonthLabels()`, `drawWeekdayLabels()`, and `updateTooltip()` to use these cached properties.

Co-authored-by: chatgpt-codex-connector[bot] <199175422+chatgpt-codex-connector[bot]@users.noreply.github.com>

Co-authored-by: debugtheworldbot <62830430+debugtheworldbot@users.noreply.github.com>
@google-labs-jules
Copy link
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @debugtheworldbot, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the performance of the ActivityHeatmapView by addressing a common performance bottleneck in macOS/iOS development: the frequent instantiation of DateFormatter and Calendar objects. By caching these objects as lazy properties, the view avoids unnecessary CPU cycles and memory allocations during redraws and layout calculations, leading to a smoother and more responsive user experience, especially during animations or resizing.

Highlights

  • Performance Optimization: Introduced lazy-initialized private properties for Calendar and DateFormatter instances within ActivityHeatmapView to prevent their repeated, expensive creation during drawing cycles.
  • Resource Caching: Cached calendar, monthFormatter, weekdaySymbols, and tooltipDateFormatter to improve efficiency.
  • Code Refactoring: Updated recalculateLayout(), drawMonthLabels(), drawWeekdayLabels(), and updateTooltip() methods to utilize the newly cached properties, removing redundant object instantiations.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • KeyStats/ActivityHeatmapView.swift
    • Added lazy private properties for calendar, monthFormatter, weekdaySymbols, and tooltipDateFormatter.
    • Removed direct Calendar.current instantiation from recalculateLayout().
    • Removed direct Calendar.current and DateFormatter instantiation from drawMonthLabels().
    • Removed direct Calendar.current and DateFormatter instantiation from drawWeekdayLabels().
    • Updated drawWeekdayLabels() to use the cached weekdaySymbols.
    • Removed direct DateFormatter instantiation from updateTooltip() and utilized the cached tooltipDateFormatter.
Activity
  • PR created automatically by Jules for task 13101833943979519934 started by @debugtheworldbot.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request effectively optimizes the ActivityHeatmapView by introducing lazy properties for DateFormatter and Calendar instances. This change prevents repeated, expensive object creation during drawing cycles, which is a common performance bottleneck in AppKit/UIKit applications. The approach aligns well with Apple's performance optimization guidelines and should lead to reduced CPU usage and smoother UI performance.

Comment on lines +36 to +40
private lazy var weekdaySymbols: [String] = {
let formatter = DateFormatter()
formatter.locale = Locale.current
return formatter.shortWeekdaySymbols ?? ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
}()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The weekdaySymbols lazy property currently initializes a DateFormatter solely to retrieve shortWeekdaySymbols. While this is lazy, DateFormatter is an expensive object to create. The Calendar object, which is already cached as self.calendar, provides shortWeekdaySymbols directly. Using self.calendar.shortWeekdaySymbols would be more efficient and avoid an unnecessary DateFormatter instantiation.

    private lazy var weekdaySymbols: [String] = {
        return calendar.shortWeekdaySymbols ?? ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
    }()

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jules fix

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch! I've simplified weekdaySymbols to use the cached calendar object instead of creating a new DateFormatter instance. I've also pre-calculated the 3-character prefixes and converted them to String once during initialization to avoid redundant work in the draw loop.

Copy link
Contributor

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 83d63b9994

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

private var gridWidth: CGFloat = 0

// MARK: - 缓存
private lazy var calendar = Calendar.current
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use autoupdating calendar for cached date computations

Caching Calendar.current in a lazy property captures a snapshot of calendar settings at first access, so long-running sessions can render stale weekday alignment after the user changes region/first-weekday or time zone in macOS settings. recalculateLayout() and drawWeekdayLabels() now depend on this cached value, which can misplace cells and labels until restart, whereas the previous code re-read Calendar.current on each call. Use Calendar.autoupdatingCurrent (or refresh the cache on locale/time-zone change notifications) to preserve correct rendering.

Useful? React with 👍 / 👎.

@debugtheworldbot debugtheworldbot deleted the performance-cache-date-formatters-13101833943979519934 branch February 27, 2026 03:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant