perf(serialization): 优化颜色模块的序列化性能

使用直接序列化结构代替中间JSON对象,减少内存分配和转换开销
This commit is contained in:
徐涛 2025-07-18 13:47:45 +08:00
parent 137079e5c6
commit 600c8c92ce
2 changed files with 24 additions and 23 deletions

View File

@ -3,8 +3,7 @@ use std::sync::Arc;
use linked_hash_map::LinkedHashMap; use linked_hash_map::LinkedHashMap;
use palette::{Oklch, color_difference::Wcag21RelativeContrast, luma::Luma}; use palette::{Oklch, color_difference::Wcag21RelativeContrast, luma::Luma};
use serde::Serialize; use serde::{Serialize, ser::SerializeStruct};
use serde_json::json;
use crate::{ use crate::{
convert::{map_oklch_to_luma, map_oklch_to_srgb_hex}, convert::{map_oklch_to_luma, map_oklch_to_srgb_hex},
@ -281,15 +280,14 @@ impl Serialize for ColorSet {
let on_root = map_oklch_to_srgb_hex(&self.on_root); let on_root = map_oklch_to_srgb_hex(&self.on_root);
let on_disabled = map_oklch_to_srgb_hex(&self.on_disabled); let on_disabled = map_oklch_to_srgb_hex(&self.on_disabled);
let color_set_object = json!({ let mut state = serializer.serialize_struct("ColorSet", 6)?;
"root": root, state.serialize_field("root", &root)?;
"hover": hover, state.serialize_field("hover", &hover)?;
"active": active, state.serialize_field("active", &active)?;
"focus": focus, state.serialize_field("focus", &focus)?;
"disabled": disabled, state.serialize_field("disabled", &disabled)?;
"onRoot": on_root, state.serialize_field("onRoot", &on_root)?;
"onDisabled": on_disabled, state.serialize_field("onDisabled", &on_disabled)?;
}); state.end()
color_set_object.serialize(serializer)
} }
} }

View File

@ -1,7 +1,7 @@
use internment::Intern;
use linked_hash_map::LinkedHashMap; use linked_hash_map::LinkedHashMap;
use palette::Oklch; use palette::Oklch;
use serde::Serialize; use serde::{Serialize, ser::SerializeStruct};
use serde_json::Value;
use crate::convert::map_oklch_to_srgb_hex; use crate::convert::map_oklch_to_srgb_hex;
@ -77,20 +77,23 @@ impl Swatch {
} }
} }
fn get_static_str(s: &str) -> &'static str {
Intern::new(s.to_string()).as_ref()
}
impl Serialize for Swatch { impl Serialize for Swatch {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where where
S: serde::Serializer, S: serde::Serializer,
{ {
let swatch_object = SWATCH_LIGHTINGS let mut state = serializer.serialize_struct("Swatch", SWATCH_LIGHTINGS.len())?;
.iter()
.map(|l| {
let color = self.get_hex(*l);
let key = format!("{l:02}");
(key, color)
})
.collect::<Value>();
swatch_object.serialize(serializer) for l in SWATCH_LIGHTINGS {
let color = self.get_hex(l);
let key: &'static str = get_static_str(&format!("{l:02}"));
state.serialize_field(key, &color)?;
}
state.end()
} }
} }