在 io.js 中使用 smalloc

use of smalloc in io.js

io.js is out this month, I was reading the docs when I found smalloc io.js 中引入的新模块的第一个版本。

直到今天,我从未觉得有必要在 JavaScript 这样做。

我的问题是:

  1. I wonder if there is really a need of raw memory allocation in javscript using smalloc?

  2. If its needed then why?

  3. what would be the use case for using smalloc?

  4. and if not then why did io.js members add this module?

它还说

可以指定您想要的外部数组数据类型。 smalloc.Types.

中列出了所有可能的选项

用法示例:

var doubleArr = smalloc.alloc(3, smalloc.Types.Double);

这里是分配支持的类型列表

smalloc.Types#

Int8
Uint8
Int16
Uint16
Int32
Uint32
Float
Double
Uint8Clamped
  1. Are we trying to make javascript a strongly typed language?

首先,缓冲区由 smalloc 模块支持,这个模块不是由 io.js 开发人员添加的,它是在 node 0.11 分支中启动的,io.js 只是导入它。原始内存分配意味着较低级别的内存操作,因此 - 更快的操作,更好的性能,这是 node.jsio.js 的目标。因此,如果您需要在二进制世界中实现某些东西而不受当前 Buffer API 的限制,您应该使用 smalloc 来创建您自己的内存操作方式。正如文档所说:

This can be used to create your own Buffer-like classes. No other properties are set, so the user will need to keep track of other necessary information (e.g. length of the allocation).

此外,这并不是要使 javascript 成为一种强类型语言,这只是内存操作,无法通过其他方式来确保更高的性能。

感谢@micnic 很好地回答了问题。我想提供一些关于我为什么实施 smalloc 的补充信息。

不要认为 JS 中的原始内存分配是什么奇怪的新事物。它与 Typed Arrays 在底层使用的机制类型相同。因此,在任何可以使用类型化数组的地方,您也可以使用 smalloc。 smalloc 的优点是它不会为你定义任何东西。让您的 API 拥有最大的灵活性。这也是安全的,因为当不再使用该对象时,GC 将清理您的分配。

一种用法是用于数学库。特别是在编写本机模块时。我个人将它用于棘手的性能优化,即在对象上分配内存,然后在 JS 和 C++ 之间共享该内存以启用两者之间的共享状态。这是迄今为止最快的方法,并且在 Node 和 io.js.

中带来了一些令人印象深刻的优化

请记住,您可以分配给现有对象。这就是力量所在。例如:

function Alloc(n) {
  n >>>= 0;  // uint32 conversion
  this.length = n;
  smalloc.alloc(n, this);
}

var a = new Alloc(16);

有一个简单的新构造,它只是将一个 Uint8 外部数据数组分配到实例上。

我会快速重申对您问题的回答:

  1. 我想知道在使用 smalloc 的 javscript 中是否真的需要原始内存分配?

是的。想想类型化数组。

  1. 如果需要,那为什么?

上面已经回答了。此外,搜索任何使用类型化数组的内容。

  1. 使用 smalloc 的用例是什么?

上面已经回答了。此外,开发人员正在为它寻找许多其他用途。

  1. 如果没有,那么为什么 io.js 成员添加了这个模块?

我早在 io.js 出现之前就写了它。 :)

  1. 我们是否正在努力使 javascript 成为一种强类型语言?

绝对没有。两者甚至没有关系。

更新: 由于 V8 v4.4 中的重大更改,smalloc 已标记为 "deprecated" 从 io.js v2 开始。