Node.js的文档中好像不再推荐new Buffer()方法了,看原因的时候,有这么一句:
The memory allocated for such Buffer instances is not initialized and can contain sensitive data. Such Buffer instances must be initialized manually by using either buf.fill(0) or by writing to the Buffer completely.
意思好像是说为这种方式创建的Buffer对象分配的内存并不是新申请的,而且可能会包含敏感信息?这样的Buffer实例必须手动填满。
这是为什么?
我不是计算机专业出身,有些地方不太理解。我查了下《深入浅出Node.js》的Buffer内存管理部分,确实是用的slab分配策略,小对象的话,是可能使用已经存在的slab单元的。但是使用不是应该是剩下的空白内存部分么?怎么会可能包含信息?而且为什么必须完全地手动来填满?我没学过计算机原理,这块实在不能理解,空着一块内存确实是浪费,但是为什么必须要填满。。。
PHP中文网2017-04-17 14:46:30
For example. You are the store (node), and the guests (programmers) come to eat. You provide the customers with dishes (memory blocks), but the guests will not wash the dishes after dinner (JS does not have such things as destructors).
For efficiency, you will reuse dishes (slab, memory reuse).
In the beginning, there were some brand new bowls and chopsticks for guests to use (blank memory). Gradually, all the bowls and chopsticks have been used at least once (all blank memory has been used)
new Buffer()
You gave the dishes directly to the customer. If the previous guest did not empty (destruct) the contents of the bowl, the guest can easily know whether the previous guest ate rice or millet. So guests must wash their dishes before using them.
The question is when to do the dishes.
If you use new Buffer()
, it means that you are only responsible for reusing the dishes, and the guests are responsible for cleaning the dishes before eating. And if you use Buffer.from
, you are not only responsible for reusing the bowls and chopsticks, but also cleaning them before giving them to customers, who can use the bowls and chopsticks directly.
Both methods have their own pros and cons. Unsafe allocates memory directly without initializing the memory. It is suitable for me to write 1024 bytes, so I allocate a buffer of 1024 bytes; after allocating to the buffer, I write directly and initialize without initializing it. It doesn't matter. And Buffer.alloc needs to be initialized additionally. If I don’t know how much data I want to write, but it’s just <1024, then I will use Buffer.alloc(1024). In this way, all the passwords can be read out immediately, and the subsequent parts will not be reused and the memory where the password was stored last time will be reused and the password will be read out directly.