Copy-on-write + Proxy = ?
一.简介
Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.
Immer提供了一种更方便的不可变状态操作方式
二.核心优势
其方便之处主要体现在:
只有一个(核心)API:
produce(currentState, producer: (draftState) => void): nextState不引入额外的数据结构:没有 List、Map、Set 等任何自定义数据结构,因此也不需要特殊的相等性比较方法
数据操作完全基于类型:用纯原生 API 操作数据,符合直觉
例如:
const myStructure = {
a: [1, 2, 3],
b: 0
};
const copy = produce(myStructure, () => {
// nothings to do
});
const modified = produce(myStructure, myStructure => {
myStructure.a.push(4);
myStructure.b++;
});
copy === myStructure // true
modified !== myStructure // true
JSON.stringify(modified) === JSON.stringify({ a: [1, 2, 3, 4], b: 1 }) // true
JSON.stringify(myStructure) === JSON.stringify({ a: [1, 2, 3], b: 0 }) // true
比起Immutable提供的全套数据结构及其操作 API:
const { Map } = require('immutable');
const originalMap = Map({ a: 1, b: 2, c: 3 });
const updatedMap = originalMap.set('b', 1000);
// New instance, leaving the original immutable.
updatedMap !== originalMap;
const anotherUpdatedMap = originalMap.set('b', 1000);
// Despite both the results of the same operation, each created a new reference.
anotherUpdatedMap !== updatedMap;
// However the two are value equal.
anotherUpdatedMap.equals(updatedMap);
Immer 显得太过简洁
三.实现原理
两个关键点:Copy-on-write 与 Proxy
Copy-on-write
概念
Copy-on-write (CoW or COW), sometimes referred to as implicit sharing or shadowing, is a resource-management technique used in computer programming to efficiently implement a "duplicate" or "copy" operation on modifiable resources.
写时复制(copy-on-write,简称 CoW 或 COW),也叫隐式共享(implicit sharing)或隐藏(shadowing),是计算机编程中的一种资源管理技术,用于高效地复制或拷贝可修改资源
If a resource is duplicated but not modified, it is not necessary to create a new resource; the resource can be shared between the copy and the original. Modifications must still create a copy, hence the technique: the copy operation is deferred to the first write. By sharing resources in this way, it is possible to significantly reduce the resource consumption of unmodified copies, while adding a small overhead to resource-modifying operations.
具体的,如果复制了一个资源但没有改动,就没必要创建这个新的资源,此时副本能够与原版共享同一资源,在修改时仍需要创建副本。因此,关键在于:将拷贝操作推迟到第一次写入的时候。通过这种方式来共享资源,能够显著减少无改动副本的资源消耗,而只是略微增加了资源修改操作的开销
应用
COW 策略主要应用在以下几方面:
虚拟内存管理:进程共享虚拟内存、fork()系统调用等
存储:逻辑卷管理、文件系统、数据库快照
编程语言:PHP、Qt 中的许多数据类型
数据结构:实现不可变的数据结构,如状态树
以 fork()系统调用为例

通过 COW 机制来实现进程间的内存共享,按需拷贝
Immer 与 Copy-on-write
在 Immer 中,Copy-on-write 机制用来解决拷贝数据结构产生的性能负担,如下图:

只在数据发生改变(write)时才拷贝数据结构(copy),否则共享同一个,因此:
copy === myStructure // true
modified !== myStructure // true
Proxy
Proxy 提供了一种 Hook 原生数据操作 API 的方式,例如:
const data = { a: 1 };
const proxy = new Proxy(data, {
set(target, key, value, receiver) {
console.log(`Set key = ${key}, value = ${value}`);
return Reflect.set(target, key, value, receiver);
}
});
proxy.a = 2;
// 输出 Set key = a, value = 2
data.a === 2 // true
不仅能够监听到数据变化,还允许进行操作拦截、甚至重定向:
const data = { a: 1 };
const copy = {};
const p = new Proxy(data, {
set(target, key, value, receiver) {
// 不写回data
// return Reflect.set(target, key, value, receiver);
// 全都写到copy上
Reflect.set(copy, key, value, copy);
}
});
p.a = 2;
data.a === 1 // true
copy.a === 2 // true
发现了什么?
data就这样成为了不可变的数据结构
P.S.关于 Proxy 语法及应用场景的更多信息,见proxy(代理机制)_ES6 笔记 9
Copy-on-write + Proxy
回到最初的示例:
const modified = produce(myStructure, myStructure => {
myStructure.a.push(4);
myStructure.b++;
});
我们试着将 Proxy 与 Copy-on-write 通过魔法融为一体:
function produce(data, producer) {
let copy;
const copyOnWrite = value => {
copy = Object.assign({}, value);
};
const proxy = new Proxy(data, {
set(target, key, value, receiver) {
// 写时复制
!copy && copyOnWrite(data);
// 全都写到copy上
Reflect.set(copy, key, value, copy);
}
});
producer(proxy);
return copy || data;
}
P.S.注意,这里提供的produce实现仅用来说明 Immer 原理,存在浅显的 bug,不具有实用价值
就得到了核心 API produce:
produce(currentState, producer: (draftState) => void): nextState
在 Immer 中,data之上的proxy被称为 Draft(草稿):

非常形象,在草稿上的修改(即对draftState的修改,会按 Copy-on-write 机制拷贝)不影响源数据,草稿完成(即producer执行完毕)之后,按照草稿对源数据打补丁,得到新数据
很巧妙的设计,就像 Photoshop 中的图层操作:
打开图片
新建图层,在新图层上涂涂抹抹
合并图层
参考资料
Copy-on-write + Proxy = ?的更多相关文章
- http-code 未译
1xx Informational Request received, continuing process. This class of status code indicates a provis ...
- 利用grunt-contrib-connect和grunt-connect-proxy搭建前后端分离的开发环境
前后端分离这个词一点都不新鲜,完全的前后端分离在岗位协作方面,前端不写任何后台,后台不写任何页面,双方通过接口传递数据完成软件的各个功能实现.此种情况下,前后端的项目都独立开发和独立部署,在开发期间有 ...
- RFC3261--sip
本文转载自 http://www.ietf.org/rfc/rfc3261.txt 中文翻译可参考 http://wenku.baidu.com/view/3e59517b1711cc7931b716 ...
- [security][modsecurity][nginx] nginx 与 modsecurity
参考文档: https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual#installation-for-nginx nginx不支 ...
- scrapy 常用代码
一,scrapy请求 yield scrapy.Request(url=url, dont_filter=True, callback=self.page, meta={'item': item}) ...
- java动态代理_aop2
一.什么是代理? 代理是一种常用的设计模式,其目的就是为其他对象提供一个代理以控制对某个对象的访问.代理类负责为委托类预处理消息,过滤消息并转发消息,以及进行消息被委托类执行后的后续处理. 代理模 ...
- Selenium - WebDriver Advanced Usage
Explicit Waits # Python from selenium import webdriver from selenium.webdriver.common.by import By f ...
- windows下的asp.net core开发及docker下的发布
参照下面,搭建好开发环境.Docker及配置好Docker加速器 http://www.cnblogs.com/windchen/p/6257846.html 参照下面,将windows共享目录挂载到 ...
- vue-cli3.0和element-ui及axios的安装使用
一.利用vue-cli3快速搭建vue项目 Vue CLI 是一个基于 Vue.js 进行快速开发的完整系统.有三个组件: CLI:@vue/cli 全局安装的 npm 包,提供了终端里的vue命令( ...
- Java开发中的23种设计模式详解(2)结构型
我们接着讨论设计模式,上篇文章我讲完了5种创建型模式,这章开始,我将讲下7种结构型模式:适配器模式.装饰模式.代理模式.外观模式.桥接模式.组合模式.享元模式.其中对象的适配器模式是各种模式的起源,我 ...
随机推荐
- 汉语拼音转换工具包pypinyin
#pip install pypinyin汉字转换汉语拼音 from pypinyin import lazy_pinyin,TONE,TONE2,TONE3 str="你知道我是谁吗?&q ...
- 王玉兰201771010128《面向对象程序设计(java)》第一周学习总结
第一部分:课程准备部分 填写课程学习 平台注册账号: 平台名称 注册账号 博客园:www.cnblogs.com 夜空傅说 程序设计评测:https://pintia.cn/ 2326669056@q ...
- iOS私有api检测工具使用
背景:这两天提审了一款新的APP,由于项目中使用了老版本的TZImagePicker中访问了私有API,导致提审失败. 预审经验分享: https://baijiahao.baidu.com/s?id ...
- MySQL(9)— 规范数据库设计
九.规范数据库设计 9-1.为什么要设计? 当数据库比较复杂时,我们就需要设计了! 糟糕的数据库设计: 数据冗余,浪费大量存储空间 使用物理外键,大量的增删改操作麻烦,异常 查询效率低下 良好的数据库 ...
- ZOJ2532判断边是否是割集中的边
Internship Time Limit: 5 Seconds Memory Limit: 32768 KB CIA headquarter collects data from acro ...
- Java——去除字符串中的中文
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RemoveStrChinese { priv ...
- ECharts使用教程
引入 ECharts ECharts 3 开始不再强制使用 AMD 的方式按需引入,代码里也不再内置 AMD 加载器.因此引入方式简单了很多,只需要像普通的 JavaScript 库一样用 scrip ...
- thinkphp路由简介和设置使用
use think\Route; //静态路由 Route::rule('/', 'index/index/index'); Route::rule('test', 'index/index/test ...
- PHP 数据库操作函数笔记
/建立 或者 关闭mysql服务器 @符号用于屏蔽错误信息 $link=@mysqli_connect('127.0.0.1','root','123456','php1',3306); if(mys ...
- pytest跟unittest的优势跟劣势
一.用例编写规则 1.使用unittest编写测试用例必须遵循以下规则: 1.必须首先 导入 import unittest 2.测试类必须要继承 unittest.TestCase 3.测试方法必须 ...