Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-11-20 13:57:15
Original
759 people have browsed it

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template