[Nodejs] Buffer vs String

Source: Internet
Author: User
Question

According to the official nodejs documentation, using Buffer for byte circulation is usually more efficient than converting to a String.
Is this all true?
This article uses a simple example of parsing the HTTP Request Header to solve this question.

HTTP Request Header Demo
POST /foo HTTP/1.1\r\nHost: foo.example.com\r\nContent-Length: 5\r\nConnection:keep-alive\r\nAccept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nCookie:connect.sid=OY2nKGqI3obs5lYee0JKTjhf.FDtbY1Jz5Ngw5So9Jv3MUetI5ITvrIfwgCkRw%2FcXUCk\r\nUser-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.41 Safari/535.7\r\n\r\nq=bar
Requirement

Obtains the Host value in the Header.

Buffer version
var SPACE = 0x20, // ' '    COLON = 0x3a, // 58, :    NEWLINE = 0x0a, // \n    ENTER = 0x0d; // \rexports.parse = function parse(data) {    var line_start = 0, len = data.length;    for(var i = 0 ; i 
String version
exports.parse = function parse(data) {    var lines = data.toString('ascii').split("\n");    var cut, name, host;    for (var i = 0, len = lines.length; i 
Test script
var buffer_parse = require('./string-buffer-benchmark-parse-header-buffer').parse  , string_parse = require('./string-buffer-benchmark-parse-header-string').parse;var data = new Buffer('POST /foo HTTP/1.1\r\nHost: foo.example.com\r\nContent-Length: 5\r\nConnection:keep-alive\r\nAccept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nCookie:connect.sid=OY2nKGqI3obs5lYee0JKTjhf.FDtbY1Jz5Ngw5So9Jv3MUetI5ITvrIfwgCkRw%2FcXUCk\r\nUser-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.41 Safari/535.7\r\n\r\nq=bar');//console.log(buffer_parse(data));//console.log(string_parse(data), data.length);var n = 1000000;var start = new Date();for(var i = 0; i 
Test Results
$ node string-buffer-benchmark.jsbuffer_parse take: 1888 msstring_parse take: 4948 ms
Conclusion

Buffer is much faster than String.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.