0
0

日時の値について。どの型を使用するか? ISO 8601? Timestamp?

Last updated at Posted at 2023-11-18

目的

  • 日時の値について、以下どちら (または他) を使うかを決めたい。
    • ISO 8601 Date and time string (e.g. 2023-11-18T08:43:53+09:00)
    • UNIX Timestamp (e.g. 1700264648)

結論

Timestampを使用する。
理由は、パフォーマンスが ISO 8601 に比べて3倍ほど早いので

ISO 8601

Pros

  • ログやデバッガで見る時、人間が読みやすい

Cons

  • Timestamp より遅い
  • タイムゾーン情報を扱わねばならず、欠落せぬよう実装に注意が必要

Timestamp

Pros

Cons

パフォーマンス測定

以下の処理を ChatGPT 先生に相談してみた

  • 日時同士の比較
  • Date instance への変換

code

const measurePerformance = (operation, iterations = 10_000_000) => {
  const start = performance.now()
  for (let i = 0; i < iterations; i++) {
    operation()
  }
  const end = performance.now()
  return end - start
}

// warm up
measurePerformance(() => new Date(), 1_000_000)

// test: comparison
{
  const performanceA = measurePerformance(() => "2023-11-18T08:43:53+09:00" < "2023-11-18T08:43:54+09:00")
  const performanceB = measurePerformance(() => 1700264648 < 1700264649)

  // result
  console.log("# Performance of ISO8601 comparison:")
  console.log(performanceA + " ms")

  console.log("# Performance of Timestamp comparison:")
  console.log(performanceB + " ms")
}

// test: convert to Date instance
{
  const performanceA = measurePerformance(() => new Date("2023-11-18T08:43:53+09:00"))
  const performanceB = measurePerformance(() => new Date(1700264648))

  // result
  console.log("# Performance of ISO8601 convert:")
  console.log(performanceA + " ms")

  console.log("# Performance of Timestamp convert:")
  console.log(performanceB + " ms")
}

結果例

  • MacBook pro M1 で実行した結果、Timestamp の方が 3 倍近く速い
# Performance of ISO8601 comparison:
102.27612501382828 ms
# Performance of Timestamp comparison:
37.01020801067352 ms

# Performance of ISO8601 convert:
1311.1170000135899 ms
# Performance of Timestamp convert:
357.1043750047684 ms
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0