perf(draft): update with_data_modify to use T instead of Box<T> for better performance

Performance improved around 11.7%, avoid to allocate stack and copy to heap.
This commit is contained in:
Tunglies
2025-12-30 17:46:30 +08:00
parent 772b87e733
commit c06c15450f
2 changed files with 6 additions and 6 deletions

View File

@@ -71,13 +71,13 @@ impl<T: Clone> Draft<T> {
pub async fn with_data_modify<F, Fut, R>(&self, f: F) -> Result<R, anyhow::Error>
where
T: Send + Sync + 'static,
F: FnOnce(Box<T>) -> Fut + Send,
Fut: std::future::Future<Output = Result<(Box<T>, R), anyhow::Error>> + Send,
F: FnOnce(T) -> Fut + Send,
Fut: std::future::Future<Output = Result<(T, R), anyhow::Error>> + Send,
{
let (local, original_arc) = {
let guard = self.inner.read();
let arc = Arc::clone(&guard.0);
(Box::new((*arc).clone()), arc)
((*arc).clone(), arc)
};
let (new_local, res) = f(local).await?;
let mut guard = self.inner.write();

View File

@@ -195,7 +195,7 @@ mod tests {
// 使用 with_data_modify 异步(立即就绪)地更新 committed
let res = block_on_ready(draft.with_data_modify(|mut v| async move {
v.enable_auto_launch = Some(true);
Ok((Box::new(*v), "done")) // Dereference v to get Box<T>
Ok((v, "done"))
}));
assert_eq!(
{
@@ -217,7 +217,7 @@ mod tests {
#[allow(clippy::unwrap_used)]
let err = block_on_ready(draft.with_data_modify(|v| async move {
drop(v);
Err::<(Box<IVerge>, ()), _>(anyhow!("boom"))
Err::<(IVerge, ()), _>(anyhow!("boom"))
}))
.unwrap_err();
@@ -243,7 +243,7 @@ mod tests {
#[allow(clippy::unwrap_used)]
block_on_ready(draft.with_data_modify(|mut v| async move {
v.enable_auto_launch = Some(false); // 与草稿不同
Ok((Box::new(*v), ())) // Dereference v to get Box<T>
Ok((v, ()))
}))
.unwrap();