JS整除運算

0x00 方法

Math.ceil(x/y);   // 向上整除 4/3=2;
Math.floor(x/y);  // 向下整除 4/3=1;
Math.round(x/y);  // 四捨五入 5/2=3 5/4=1;
parseInt(x/y);    // 丟棄小數部分,保留整數部分; 

0x01 性能

function fn1(x, y){let t = Math.ceil(x/y)}
function fn2(x, y){let t = Math.floor(x/y)}
function fn3(x, y){let t = Math.round(x/y)}
function fn4(x, y){let t = parseInt(x/y)}
function test(fn, n){
  let start = new Date().getTime();
  // 137437	是一個質數
  for(let i=0; i<n; i++){fn(i, 137437)}
  let end = new Date().getTime();
  console.log(n, end-start)
}
// 測試
test(fn1, 10000000);  // 13ms
test(fn2, 10000000);  // 89ms
test(fn3, 10000000);  // 72ms
test(fn4, 10000000);  // 232ms

0x02 附

  • 個人是個菜鳥,測試準確性不敢保證;
  • 測試使用的瀏覽器內核:Chromium 71.0.3578.98 (64位)
  • 測試時間:Sun Mar 10 2019 10:16:41 GMT+0800 (中國標準時間)
  • 因準確性不敢保證,因此轉載請註明出處以便溯源
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章