Readonly和Parallel
提示
注意:向 readonly 或 parallel 变量赋值需使用 ':=' 符号而不是 '=' 符号
概述
对应GS中readonly和parallell两个关键字 readonly可以修饰成员变量 parallel可以修饰成员变量和方法
只读变量
- readonly的变量,每次赋值都会深拷贝,如果写得很频繁,开销很大,出现过很多次ro变量频繁赋值导致的性能问题,看实际底层实现的代码不难发现,每次RO赋值时的深拷贝
void VmBase::do_RO_ASSIGN(Object* this_ob, ValueType type, ValueSubType sub_type, ValueAttrib attr, Value* p1, Value* p2)
{
// RO assign do not need to call check_before_write,
// since multiple assignments in different threads may occur
// at the same time, which will cause assertion in check_before_write
// Call this_ob->_check_after_written_no_assert() directly
// Assign to readonly object's var
// Allocate new readonly value if the value is reference value
if (p2->is_reference_value() && p2->m_reference->is_modifiable())
{
// Clone the source value & make it readonly
auto* current_domain = Coroutine::get_current_co_domain();
CO_VALUE(cloned_val);
p2->clone_entirely(&cloned_val, current_domain, current_domain);
ReferenceRoParallel::make_readonly(&cloned_val);
_check_and_assign(type, sub_type, attr, p1, &cloned_val);
}
else
_check_and_assign(type, sub_type, attr, p1, p2);
// Notify this_ob was changed if it an old unit
this_ob->_check_after_written_no_assert();
}
举个例子:
map m = get_system_info();
void run()
{
map s = get_system_info();
int t = time.time_ms();
for (int i = 1 upto 1000000)
m = s;
t = time.time_ms() - t;
printf("t = %dms\n", t);
}
run();