lkang2 / glmatrix

Automatically exported from code.google.com/p/glmatrix
0 stars 0 forks source link

avoid i / len #4

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
in mat4.rotate:

        if (len != 1) {
                var ilen = 1 / len;
                x *= ilen; y *= ilen; z *= ilen;
        }

to 
        if (len != 1) {
                x /= len; y /= len; z /= len;
        }

and vec3.normalize:

                dest[0] = x / len;
                dest[1] = y / len;
                dest[2] = z / len;

Original issue reported on code.google.com by danielhe...@gmail.com on 5 Jun 2010 at 10:05

GoogleCodeExporter commented 8 years ago
I've been curious about this, and I haven't been able to get a decisive 
benchmark on it 
either way. In traditional native code a multiply is almost always faster than 
a 
divide, so caching the inverse and multiplying is very commonplace. In select 
circumstances in javascript, however, it seems that doing the divides directly 
can 
actually be faster. Can anyone provide me with a good explanation for this?

Original comment by Tojiro@gmail.com on 5 Jun 2010 at 4:56

GoogleCodeExporter commented 8 years ago
Looks like it is indeed slower, at least in my microbenchmark.

<html>
<script type="text/javascript">

var d = new Date();
var i = 10.4;
var x = 10.1;
var y = 15.1;
var z = 90.1;
for (var a = 0; a < 10000000; a++) {
    var il = 1/i;
    x*=il;
    y*=il;
    z*=il;
}
var e = new Date() - d;

var f = new Date();
var i = 10.4;
var x = 10.1;
var y = 15.1;
var z = 90.1;
for (var a = 0; a < 10000000; a++) {
    x/=i;
    y/=i;
    z/=i;
}
var g = new Date() - f;

alert(e);
alert(g);
</script>
</html>

Original comment by danielhe...@gmail.com on 5 Jun 2010 at 7:31

GoogleCodeExporter commented 8 years ago

Original comment by Tojiro@gmail.com on 12 Jun 2010 at 5:19

GoogleCodeExporter commented 8 years ago
Running the benchmark you posted I'm getting ~1600ms for the *= version and 
~1800ms for the /= version in Chrome, but ~120ms for *= and ~95 ms for /= in 
Minefield, so we're at a bit of an impasse.

BTW: Has anyone else noticed that benchmark times ALWAYS seem extremely low on 
minefield? I know they've been putting a lot of work into it, but 13 times 
faster than chrome seems excessive. I think they may be recognizing that the 
loop has no external effect and removing most of it! :(

In any case, IF the above benchmarks are true, I would prefer to optimize 
against the browser that needs it most (in this case Chrome). So I believe that 
for the time being I will be sticking with the multiply by inverse method.

Original comment by Tojiro@gmail.com on 12 Jun 2010 at 5:46