Home >Web Front-end >JS Tutorial >Flooring Floats with Bitwise OR: Faster Than Math.floor()?

Flooring Floats with Bitwise OR: Faster Than Math.floor()?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-20 13:57:15817browse

Flooring Floats with Bitwise OR: Faster Than Math.floor()?

Flooring Numbers with Bitwise OR 0

A unique method has surfaced for flooring float numbers using a bitwise OR operator:

var a = 13.6 | 0; // a == 13

Let's delve into this technique, exploring its mechanisms and comparing it to the standard Math.floor function.

How Does It Work?

Bitwise operations operate on signed 32-bit integers. Therefore, applying a bitwise OR to a float number effectively converts it to an integer, truncating the fractional part.

Advantages Over Math.floor?

Benchmarking results suggest that this method can be marginally faster than Math.floor.

Disadvantages:

  • May not pass JavaScript linting checks
  • Limited to 32-bit signed integers
  • Comparative behavior differs from Math.floor:

    • Math.floor(NaN) === NaN
    • (NaN | 0) === 0

The above is the detailed content of Flooring Floats with Bitwise OR: Faster Than Math.floor()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn