Law of cosines

JavaScript performance comparison

Test case created by Binyamin

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    if (typeof Number.prototype.toRad === 'undefined') {
        Number.prototype.toRad = function() {
            return this * Math.PI / 180;
        };
    }
   
    function lawofcosines1(lat1, lon1, lat2, lon2) {
        var R = 6371000,
            a = Math.sin(lat1.toRad()) * Math.sin(lat2.toRad()),
            b = Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.cos((lon2 - lon1).toRad()),
            c = Math.acos(a + b),
            d = R * c;
   
        return d.toFixed(2);
    }
   
    function lawofcosines2(lat1, lon1, lat2, lon2) {
        var lat1 = lat1.toRad(),
            lat2 = lat2.toRad(),
            a = Math.sin(lat1) * Math.sin(lat2),
            b = Math.cos(lat1) * Math.cos(lat2) * Math.cos((lon2 - lon1).toRad()),
            c = Math.acos(a + b);
   
        return (6371000 * c).toFixed(2);
    }
   
    function lawofcosines3(lat1, lon1, lat2, lon2) {
        var lat1 = lat1.toRad(),
            lat2 = lat2.toRad(),
            a = Math.sin(lat1) * Math.sin(lat2),
            b = Math.cos(lat1) * Math.cos(lat2) * Math.cos((lon2 - lon1).toRad()),
            c = Math.acos(a + b),
            d = 6371000 * c;
   
        return d.toFixed(2);
    }
   
    function lawofcosines4(lat1, lon1, lat2, lon2) {
        var lat1 = lat1.toRad(),
            lat2 = lat2.toRad(),
            a = Math.sin(lat1) * Math.sin(lat2),
            b = Math.cos(lat1) * Math.cos(lat2) * Math.cos((lon2 - lon1).toRad()),
            c = Math.acos(a + b),
            d = (6371000 * c).toFixed(2);
   
        return d;
    }
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
lawofcosines1
lawofcosines1(-31.965379, 115.822077, -33.85789, 151.214806);
pending…
lawofcosines2
lawofcosines2(-31.965379, 115.822077, -33.85789, 151.214806);
pending…
lawofcosines3
lawofcosines3(-31.965379, 115.822077, -33.85789, 151.214806);
pending…
lawofcosines4
lawofcosines4(-31.965379, 115.822077, -33.85789, 151.214806);
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment