当只需要部分时,如何避免克隆整个大型结构以发送到线程?
How could I avoid cloning the entirety of a large struct to send to a thread when only parts are needed?
我的用例:
- 我有一个很大的复杂结构。
- 我想拍下这个结构的快照,将它发送到线程做一些计算。
- 此结构中的许多大字段不需要计算。
- 结构中的许多字段是部分必需的(一个字段可能是一个结构,并且只需要该结构中的几个参数)。
目前我只是调用 .clone()
并将整个结构的克隆传递给线程。
很难给出一个很好的例子,但这是我目前方法的总结:
use tokio::task;
fn main() {
let compex_struct = ComplexStruct::new(...);
// some extra async stuff I don't think is 100% neccessary to this question
let future = async_function(compex_struct.clone()); // Ideally not cloning whole struct
// some extra async stuff I don't think is 100% neccessary to this question
}
fn async_function(complex_struct:ComplexStruct) -> task::JoinHandle<_> {
task::spawn_blocking(move || {
// bunch of work, then return something
})
}
我目前的工作想法是有一个单独的结构,例如 ThreadData
,它用 ThreadData::new(ComplexStruct)
实例化并有效地克隆所需的字段。然后我将 ThreadData
传递给线程。
这个问题的最佳解决方案是什么?
我想你已经回答了你自己的问题。如果您只是在寻找验证,我相信只重构需要的部分是个好主意。您可能会找到简化代码的方法,但性能提升似乎是您的理由。我们看不到这方面的基准,但也许您想跟踪它。
这部分只是我的意见,但您可以 ThreadData::from()
代替 ThreadData::new()
,或者更好的是 impl From<ComplexStruct> for ThreadData {}
。如果它只有一个目的那么它并不重要,但如果 ThreadData 将在不同的上下文中使用,我喜欢保持“新”/“来自”函数可用于一般实例。否则我最终会得到 Struct::from_this()
、Struct::from_that()
或 Struct::from_some_random_input()
。
我的用例:
- 我有一个很大的复杂结构。
- 我想拍下这个结构的快照,将它发送到线程做一些计算。
- 此结构中的许多大字段不需要计算。
- 结构中的许多字段是部分必需的(一个字段可能是一个结构,并且只需要该结构中的几个参数)。
目前我只是调用 .clone()
并将整个结构的克隆传递给线程。
很难给出一个很好的例子,但这是我目前方法的总结:
use tokio::task;
fn main() {
let compex_struct = ComplexStruct::new(...);
// some extra async stuff I don't think is 100% neccessary to this question
let future = async_function(compex_struct.clone()); // Ideally not cloning whole struct
// some extra async stuff I don't think is 100% neccessary to this question
}
fn async_function(complex_struct:ComplexStruct) -> task::JoinHandle<_> {
task::spawn_blocking(move || {
// bunch of work, then return something
})
}
我目前的工作想法是有一个单独的结构,例如 ThreadData
,它用 ThreadData::new(ComplexStruct)
实例化并有效地克隆所需的字段。然后我将 ThreadData
传递给线程。
这个问题的最佳解决方案是什么?
我想你已经回答了你自己的问题。如果您只是在寻找验证,我相信只重构需要的部分是个好主意。您可能会找到简化代码的方法,但性能提升似乎是您的理由。我们看不到这方面的基准,但也许您想跟踪它。
这部分只是我的意见,但您可以 ThreadData::from()
代替 ThreadData::new()
,或者更好的是 impl From<ComplexStruct> for ThreadData {}
。如果它只有一个目的那么它并不重要,但如果 ThreadData 将在不同的上下文中使用,我喜欢保持“新”/“来自”函数可用于一般实例。否则我最终会得到 Struct::from_this()
、Struct::from_that()
或 Struct::from_some_random_input()
。