Skip to content

Commit

Permalink
perf: improve repeated timezone lookups
Browse files Browse the repository at this point in the history
Perform a timezone lookup only once at initialization, assuming that the timezone doesn't change during exection.
  • Loading branch information
erwinvaneijk committed Jan 21, 2025
1 parent adda6e5 commit 2e8ebbf
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions src/output/render/times.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::sync::OnceLock;

// SPDX-FileCopyrightText: 2024 Christina Sørensen
// SPDX-License-Identifier: EUPL-1.2
//
Expand All @@ -15,12 +17,23 @@ pub trait Render {
fn render(self, style: Style, time_format: TimeFormat) -> TextCell;
}

// Assume that the timezone is constant for the duration of the program.
static INITIAL_TIMEZONE: OnceLock<Option<Tz>> = OnceLock::new();

fn initialize_timezone() -> Option<Tz> {
let timezone_str = iana_time_zone::get_timezone();
timezone_str.map_or(None, |tz_str| {
Some(
tz_str
.parse()
.unwrap_or_else(|_| panic!("The timezone cannot be parsed: {tz_str}")),
)
})
}

impl Render for Option<NaiveDateTime> {
fn render(self, style: Style, time_format: TimeFormat) -> TextCell {
let datestamp = if let Ok(timezone_str) = iana_time_zone::get_timezone() {
let timezone: Tz = timezone_str
.parse()
.unwrap_or_else(|_| panic!("The timezone cannot be parsed: {timezone_str}"));
let datestamp = if let Some(timezone) = INITIAL_TIMEZONE.get_or_init(initialize_timezone) {
if let Some(time) = self {
let time_offset = timezone.offset_from_utc_datetime(&time).fix();
time_format.format(&DateTime::<FixedOffset>::from_naive_utc_and_offset(
Expand Down

0 comments on commit 2e8ebbf

Please sign in to comment.