0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ビット演算を活用して処理速度を高速化する方法 (for TypeScript)

Last updated at Posted at 2025-03-31

初め

%演算じゃなくビット演算で最適化をすることでどのくらい高速化するのか気になってテストしました。

Code

const startTime0 = performance.now();
const arr = [...Array(1000000)].map((_, i) => i);
const endTime0 = performance.now();
console.log(
  `Execution Initialization: ${(endTime0 - startTime0).toFixed(2)} ms`
);

const startTime1 = performance.now();

// %計算
const evenNumbers = arr.filter((num) => num % 2 === 0);
const endTime1 = performance.now();
console.log(
  `Execution time with % 2: ${(endTime1 - startTime1).toFixed(2)} ms`
);

const startTime2 = performance.now();

//&演算
const evenNumbersBitwise = arr.filter((num) => (num & 1) === 0);
const endTime2 = performance.now();
console.log(
  `Execution time with & 1: ${(endTime2 - startTime2).toFixed(2)} ms`
);

Result

$ node test2.js
Execution Initialization: 22.61 ms
Execution time with % 2: 25.86 ms
Execution time with & 1: 24.48 ms
$ node test2.js
Execution Initialization: 29.62 ms
Execution time with % 2: 24.02 ms
Execution time with & 1: 24.64 ms
$ node test2.js
Execution Initialization: 22.40 ms
Execution time with % 2: 24.04 ms
Execution time with & 1: 22.34 ms
$ node test2.js
Execution Initialization: 30.47 ms
Execution time with % 2: 26.98 ms
Execution time with & 1: 23.18 ms

最後

ビット演算を使用することで、計算速度が大幅に向上することがわかりました。もし、最適化が必要な場合はビット演算を試すことが効果的です。

ただし、ビット演算は理解が難しいと感じるチームメンバーもいるかもしれません。その場合、適切にドキュメントを作成して説明を加えることが重要だと思います。

ps.コードに問題がありました。😭
@yoshi389111 ありがとうございます。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?