javascript - Node - Bitwise Calculations with IP Addresses -
i've made dns tool in node , know how can optimize performance of tolong()
using bitwise? i've included of pseudo-code reference.
var _parser = function (ip) { homecoming ip.split('.').map(function (i) { homecoming | 0; }); }, _isipv4 = function (ip) { var i, isvalid = true, octets = _parser(ip); if (octets.length !== 4) { isvalid = false; } octets.foreach(function (octet) { if (octet < 0 || octet > 255) { isvalid = false; } }); homecoming isvalid; }; tolong: function (ip) { var i, converted, octets = _parser(ip); if (!_isipv4(ip)) { throw 'invalid ipv4 address!'; } converted = 0; (i = 0; < octets.length; i++) { converted += octets[i] * math.pow(256, (3 - i)); } homecoming converted; };
i'd recommend unrolling loops , ditching function calls. added revision jsperf created @imsky: http://jsperf.com/node-bitwise-calculations-with-ip-addresses/6 looks ~5x faster original.
var unrolledlong = function(ip) { var octets = ip.split('.'); if (octets.length !== 4) throw "invalid ipv4 address!"; octets[0] = octets[0] | 0; octets[1] = octets[1] | 0; octets[2] = octets[2] | 0; octets[3] = octets[3] | 0; if ((octets[0] < 0 || octets[0] > 255) || (octets[1] < 0 || octets[1] > 255) || (octets[2] < 0 || octets[2] > 255) || (octets[3] < 0 || octets[3] > 255)) { throw 'invalid ipv4 address!'; } // >>> 0 calls forcefulness number unsigned value. homecoming octets[3] + ((octets[2] << 8) >>> 0) + ((octets[1] << 16) >>> 0) + ((octets[0] << 24) >>> 0); };
if bitwise math little weird, can utilize multiplication:
var unrolledlong = function(ip) { var octets = ip.split('.'); if (octets.length !== 4) throw "invalid ipv4 address!"; octets[0] = octets[0] | 0; octets[1] = octets[1] | 0; octets[2] = octets[2] | 0; octets[3] = octets[3] | 0; if ((octets[0] < 0 || octets[0] > 255) || (octets[1] < 0 || octets[1] > 255) || (octets[2] < 0 || octets[2] > 255) || (octets[3] < 0 || octets[3] > 255)) { throw 'invalid ipv4 address!'; } // >>> 0 calls forcefulness number unsigned value. homecoming octets[3] + (octets[2] * 0x100) + (octets[1] * 0x10000) + (octets[0] * 0x1000000); };
javascript node.js bit-manipulation
No comments:
Post a Comment