Math.sincos(x)?
Nicolas B. Pierron
nicolas.b.pierron at mozilla.com
Fri Jun 23 10:00:48 UTC 2017
Hi Robert,
On Thu, Jun 22, 2017 at 6:02 PM, Robert Poor <rdpoor at gmail.com> wrote:
> How often have you seen code that calls Math.sin() and Math.cos() with
> the same argument, e.g:
>
> x = r * Math.cos(theta);
> y = r * Math.sin(theta);
>
> ? This trope is repeated for polar coordinates, complex arithmetic, FTTs, etc.
>
> However, most implementations for cos(theta) actually generate
> sin(theta) as a "byproduct" (and vice-versa). Since trigonometric
> functions are relatively expensive, and this is a common pattern,
> wouldn't it make sense to define a function that returns cos(theta)
> and sin(theta) at the same time?
For your information, the optimizing compiler of SpiderMonkey already
try to optimize consecutive calls to cos and sin by the sincos
function when possible.
I do not know if other optimizing compilers are doing this
optimization as well, but I would expect that it would be quite easy
to add.
http://searchfox.org/mozilla-central/rev/3291398f10dcbe192fb52e74974b172616c018aa/js/src/jit/Ion.cpp#1310
On Thu, Jun 22, 2017 at 6:02 PM, Robert Poor <rdpoor at gmail.com> wrote:
> A polyfill might look like this:
>
> function sincos(theta) {
> return { sin: sin(theta), cos: cos(theta) };
> }
I would expect all engines to use escape analysis to remove this
object allocation, when this function is inlined.
Until this code gets inlined, by allocating an object this code will
add pressure to the nursery of the garbage collector. This will also
add memory writes/reads to/from memory. Both are not desirable when
you are doing math-intensive operations.
--
Nicolas B. Pierron
More information about the es-discuss
mailing list