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:
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 usetoString()
which allocates a newString
(hint: slow) and then create a newBuffer
based on the size of that string.You're just swapping bytes (
[]
on buffers is not a character index) here itwill be way fasterwould 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.xtoString
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.
精彩评论