开发者

Performing .replace() on Buffer (Node.js) contents?

This is quite a newb question, but I have not found any reliable answers through Google/SO/Etc.

If you have content in a Buffer, wha开发者_StackOverflow中文版t is the best pattern for running a .replace() on that content?

Do you simply pull out the content with .toString(), run replace(), then put it back in the Buffer? Or is there a better way?

Thanks


Depends on what you want to replace, Buffers don't reallocate them self, the Buffer object you have in JavaScript is merely a "pointer" into an external memory region (I'm speaking specifically about Node.js 3.x here, the old "SlowBuffers" in 2.x work in a different way).

So there are two possible scenarios:

  1. Your replacement value's length is <> the value that's being replaced. In this case there's not much you can do, you need to use toString() which allocates a new String (hint: slow) and then create a new Buffer based on the size of that string.

  2. You're just swapping bytes ([] on buffers is not a character index) here it will be way faster would be faster on 2.x to just use a plain loop, and perform the replacement your self, since there is nearly no allocation overhead (Node allocates a new int with the same value as the one that was written) but on 3.x toString is fine for 99% of the time.

But what you really want to watch out for is, that you don't write gigantic strings to sockets, because that's really slow under 2.x.
Due to the fact that V8 can move the strings in memory at any time, Node 2.x needs to copy them out before passing their pointer to the OS. This has been fixed with some hacks on V8 in 3.x.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜