From b3326032f67fbc83810eb0ecfad635d586a9f802 Mon Sep 17 00:00:00 2001
From: Shibo Lyu <laosb@ShibodeMac-mini.local>
Date: Sat, 14 Jun 2025 20:01:02 +0800
Subject: [PATCH] fix: Reuse JSONEncoder and JSONDecoder instances in
 TypedAppStorage

---
 Sources/TypedAppStorage/TypedAppStorage.swift | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/Sources/TypedAppStorage/TypedAppStorage.swift b/Sources/TypedAppStorage/TypedAppStorage.swift
index 2e780f2..4b11e7b 100644
--- a/Sources/TypedAppStorage/TypedAppStorage.swift
+++ b/Sources/TypedAppStorage/TypedAppStorage.swift
@@ -18,13 +18,15 @@ public protocol TypedAppStorageValue: Codable, Sendable {
 public struct TypedAppStorage<Value: TypedAppStorageValue>: DynamicProperty {
   private var appStorage: AppStorage<String>
   private var initialValue: Value
+  private let encoder = JSONEncoder()
+  private let decoder = JSONDecoder()
 
   /// Store and fetch value from the defined store, with a predefined default value.
   ///
   /// This default value if defined is preferred over ``TypedAppStorageValue/defaultValue``.
   public init(wrappedValue: Value, store: UserDefaults? = nil) {
     initialValue = wrappedValue
-    let initialData = try? JSONEncoder().encode(wrappedValue)
+    let initialData = try? encoder.encode(wrappedValue)
     let initialString =
       (initialData == nil ? nil : String(data: initialData!, encoding: .utf8))
       ?? ""
@@ -48,11 +50,11 @@ public struct TypedAppStorage<Value: TypedAppStorageValue>: DynamicProperty {
       guard let data = appStorage.wrappedValue.data(using: .utf8) else {
         return initialValue
       }
-      return (try? JSONDecoder().decode(Value.self, from: data)) ?? initialValue
+      return (try? decoder.decode(Value.self, from: data)) ?? initialValue
     }
     nonmutating set {
       guard
-        let newData = try? JSONEncoder().encode(newValue),
+        let newData = try? encoder.encode(newValue),
         let newString = String(data: newData, encoding: .utf8)
       else { return }
       appStorage.wrappedValue = newString