# JavaScript inet_aton functions comparison

I came across this stun.js code and found one interesting implementation of inet_aton functions. I curious of its formula and equation.

```function inet_aton(a) {
var d = a.split('.');
return ((((((+d)*256)+(+d))*256)+(+d))*256)+(+d);
}
```

I written a simple Node.JS test script just to evaluate, calculate different implementations of inet_aton, and here is my findings:

```function inet_aton(a) {
var d = a.split('.');
return ((((((+d)*256)+(+d))*256)+(+d))*256)+(+d);
}
function inet_aton_b(ip){
var a = new Array();
a = ip.split('.');
return((a < < 24) >>> 0)  + ((a < < 16) >>> 0) + ((a < < 8) >>> 0) + (a >>> 0);
}

function inet_aton_c(a) {
var d = a.split('.');
return d * 256 * 256 * 256 + d * 256 * 256 + d * 256 + d;
}

var start;
start = new Date().getTime();
for(var i = 0; i < 1000000; i++) {
inet_aton('1.1.1.1')
}
console.log('elapsed:' + (new Date().getTime() - start));

start = new Date().getTime();
for(var i = 0; i < 1000000; i++) {
inet_aton_b('1.1.1.1')
}
console.log('elapsed:' + (new Date().getTime() - start));

start = new Date().getTime();
for(var i = 0; i < 1000000; i++) {
inet_aton_c('1.1.1.1')
}
console.log('elapsed:' + (new Date().getTime() - start));
```

See the first implementation run faster. The key point is lesser multiplication is performed, by factoring using simple math.

I run the same code on Java but I found different things, I can't tell which one run faster than other one. If I run the first code first, second code followed, always the second block faster than first block. If I exchange, run second code first, first code followed, always the second block faster than first block. They both run in same speed. I even use javap to view its bytecode and found second code have more instruction than first one, but might be JVM can do its optimization so that end result both code run same speed. ## Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

Posted on Categories JavaScript

## One thought on “JavaScript inet_aton functions comparison”

This site uses Akismet to reduce spam. Learn how your comment data is processed.