Skip to content

Commit af134fa

Browse files
authored
perf(plugin): Avoid data copy when transformation finished (#11223)
**Description:** When the transformation is done, we can make sure that the `transformed_result` won't be used by wasm imports. So it's safe to fetch the data from it without cloning the bytes.
1 parent b842002 commit af134fa

File tree

2 files changed

+22
-10
lines changed

2 files changed

+22
-10
lines changed

.changeset/gentle-owls-count.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
swc_plugin_runner: patch
3+
swc_core: patch
4+
---
5+
6+
perf(plugin): avoid data copy when transformation finished

crates/swc_plugin_runner/src/transform_executor.rs

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ struct PluginTransformState {
3838
#[cfg(feature = "encoding-impl")]
3939
impl PluginTransformState {
4040
fn run(
41-
&mut self,
41+
mut self,
4242
program: &PluginSerializedBytes,
4343
unresolved_mark: swc_common::Mark,
4444
should_enable_comments_proxy: Option<bool>,
@@ -67,10 +67,21 @@ impl PluginTransformState {
6767
should_enable_comments_proxy,
6868
)?;
6969

70-
// Copy guest's memory into host, construct serialized struct from raw
71-
// bytes.
72-
let transformed_result = &(*self.transform_result.lock());
73-
let ret = PluginSerializedBytes::from_bytes(transformed_result.clone());
70+
self.instance
71+
.caller()?
72+
.free(guest_program_ptr.0, guest_program_ptr.1)?;
73+
self.instance.cleanup()?;
74+
75+
// Construct serialized struct from raw bytes.
76+
// Since we have finished transformation, it's safe to fetch the data from
77+
// Arc<Mutex<T>>
78+
drop(self.instance);
79+
let transformed_result = Arc::try_unwrap(self.transform_result)
80+
.map_err(|_| {
81+
anyhow!("Failed to unwrap Arc: other references to transform_result exist")
82+
})?
83+
.into_inner();
84+
let ret = PluginSerializedBytes::from_bytes(transformed_result);
7485

7586
let ret = if returned_ptr_result == 0 {
7687
Ok(ret)
@@ -89,11 +100,6 @@ impl PluginTransformState {
89100
}
90101
};
91102

92-
self.instance
93-
.caller()?
94-
.free(guest_program_ptr.0, guest_program_ptr.1)?;
95-
self.instance.cleanup()?;
96-
97103
ret
98104
}
99105

0 commit comments

Comments
 (0)