在Buffer(Node.js)内容上执行.replace()? [英] Performing .replace() on Buffer (Node.js) contents?

查看:140
本文介绍了在Buffer(Node.js)内容上执行.replace()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常新的问题,但我没有通过Google / SO / Etc找到任何可靠的答案。

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

如果您在缓冲区中有内容,那么什么是在该内容上运行 .replace()的最佳模式?

If you have content in a Buffer, what is the best pattern for running a .replace() on that content?

您是否只需提取内容 .toString(),运行 replace(),然后将其放回缓冲区?或者有更好的方法吗?

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

谢谢

推荐答案

取决于你想要替换的是什么, Buffers 不要自己重新分配它们,你在JavaScript中的 Buffer 对象只是一个指针进入外部存储器区域(我在这里专门讲述Node.js 3.x,2.x中的旧SlowBuffers以不同的方式工作)。

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. 您的替换值的长度为<> ; 要替换的值。在这种情况下你可以做的不多,你需要使用 toString()分配一个新的 String (提示) :慢)然后根据该字符串的大小创建一个新的缓冲区

  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.x上只使用一个普通循环,并执行替换你自己,因为几乎没有分配开销(Node分配一个新的int与写入的相同的值),但在3.x toString 99%的罚款都没问题。

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.

但是你真的要注意的是,你没有给套接字写出巨大的字符串,因为那个真的在2.x下很慢。

由于V8可以在任何时候将字符串移动到内存中,Node 2.x需要在将指针传递给OS之前将其复制出来。这已经修复了3.x中V8的一些黑客攻击。

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.

这篇关于在Buffer(Node.js)内容上执行.replace()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆