javascript - 这个函数的性能可以变得更快吗?

标签 javascript optimization prototype

该函数已经告诉您它的作用,但无论如何,它会包裹 Angular 并确保它在 0-360 之间。这是 JavaScript:

Number.prototype.wrapAngle = function(){
    var d = this;
    while(d > 360){ d -= 360;};
    while(d < 0){ d += 360;};
    return d.toString();
}

我需要“wrapAngle”尽可能快!

最佳答案

为什么不使用模?

-721 % 360; // -1
390  % 360; // 30
90   % 360; // 90

所以:

Number.prototype.wrapAngle = function(){
    var d = this % 360;
    if (d < 0) { // ensure positive number.
      d += 360;
    }

    // return a number, not a string.
    // This is a math based transformation of a number, so it should be a number.
    return d; 
}

由于模数可以返回负数,但该数字总是-360更接近于零,您只需将其递增一次,如果是负数。

性能比较:http://jsperf.com/wrapangle

关于javascript - 这个函数的性能可以变得更快吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20890014/

相关文章:

javascript - XmlHttpRequest.responseText 结果?

JavaScript:相对于父级单击时增加变量值

javascript - 如何优化JS代码?

c - 用于图像处理的非常快的 memcpy?

javascript - 如何实现这个继承模式: object. object.method

javascript - ES6 类原型(prototype) - 类型解析

javascript - 与阿多尼斯 react

javascript - backbone collection fetch 不会在成功调用中运行任何东西,但可以正常获取

c++ - 在 spoj AP2 上得到错误答案

object - 在 MongoDB 中存储和检索 JavaScript 对象