缓冲区与字符串速度:为什么String更快? [英] Buffer vs String speed: Why is String faster?

查看:99
本文介绍了缓冲区与字符串速度:为什么String更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Memcached.Js 的项目,它是Memcached服务器的一个端口到Node.js。

I have this project, called Memcached.Js, which is a port of Memcached server to Node.js.

我一直在玩字符串和缓冲区,比较内存占用和性能。对于内存,毫无疑问缓冲区是正确的选择。

I've been playing arround with strings and buffers, comparing memory footprint and performance. For memory, there's no question that buffer is the right choice.

但令我惊讶的是,性能并非如此。执行字符串操作比使用缓冲区更快。这就是我的尝试:

But for my surprise the same is not true for performace. Performing string manipulation is faster than using buffer. This is what I tried:

// Option 1: data.toString() - amazing, but it's the best one
var commandDataStr = mdata.data.toString().substr(startPos, bytes);
var commandData = new Buffer(commandDataStr);

// Option 2: data.slice().toString() - the same as above... What?
var commandDataStr = mdata.data.slice(startPos, startPos + bytes).toString();
var commandData = new Buffer(commandDataStr);

// Option 3: data.slice() - bad
var commandData = mdata.data.slice(startPos, startPos + bytes);

// Option 4: data.copy() - bad as well
var commandData = new Buffer(bytes);
mdata.data.copy(commandData, 0, startPos, startPos + bytes);

完整的代码在这里:
https://github.com/dalssoft/memcached.js/blob/master/lib /memcached.ascii.commands.js#L72

测试代码: ruby​​ test / from_clients / perf_test.rb

测试显示字符串比缓冲区更快。因为它不是我所期待的,我想我可能做错了什么,但我找不到它究竟是什么。

The tests showed that Strings are faster than Buffer. Since it's not what I was expecting, I think I'm probably doing something wrong, but I can't find exactly what it is.

有人可以帮我吗?

Tks!

推荐答案

字符串内置于V8,并在VM中分配内存。添加缓冲区不是为了使所有字符串操作更快,而是表示二进制数据,其中字符串是unicode。

Strings are built-in to V8, and allocate memory within the VM. Buffers were added not to make all string operations faster, but to represent binary data, where as Strings are unicode.

当向套接字写入大量数据时,它很多以二进制格式提供数据更有效率,而不必转换为unicode。

When writing large amounts of data to a socket, it's much more efficient to have that data in binary format, vs having to convert from unicode.

因此对于常见操作,如concat,我并不感到惊讶。字符串更快。

So for common operations, like concat, I'm not surprised Strings are faster.

这篇关于缓冲区与字符串速度:为什么String更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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