Languages
[Edit]
EN

JavaScript - fastest way to negate number

4 points
Created by:
Kadeem-Craig
516

In this article, we would like to show you how to negate numbers in JavaScript.

There are three ways to negate numbers:

  1. x = -x
  2. x *= -1
  3. x = ~x + 1

1. Complexity analysis

Edit
  1. x = -x operations:
    1. read the value from the memory
    2. make the value negation
    3. write the value to memory
  2. x *= -1 (x = x * (-1)) operations:
    1. read the value from the memory
    2. make the multiplication by -1 operation
    3. write the value to memory
  3. x = ~x + 1 operations:
    1. read the value from the memory
    2. make bitwise not operation
    3. make add +1 operation
    4. write the value to memory

Notes:

  • multiplication operations are slower than bitwise and subtract operations,
  • in this case interpreter / compliler can make some optimisation,
  • amount of operations affects on performance,
  • getting and setting variables from RAM memory can be slow.

The best way is always to make a benchmark test.

2. Benchmark test example 

Edit

Note: in the above code there are 2 configuration variables:

  • testsCount - number of test repeats,
  • testSize - number of iterations per one test.

 


2.1. Notebook: Xiaomi Mi 13 with NodeJS test results

Edit

This test has been made on PC with:

  • OS: Windows 10 x64
  • Program: NodeJS x64 v10.15.1
  • CPU: Intel i5-6200u (6th generation)
  • RAM: DDR4 8GB 2133 MHz
  • SSD: SAMSUNG MZVLV256HCHP-00000

2.2. Notebook: Xiaomi Mi 13 with Google Chrome Browser test results

Edit

This test has been made on PC with:

  • OS: Windows 10 x64
  • Program: Google Chrome Version 78.0.3904.97 (Official Build) (64-bit)
  • CPU: Intel i5-6200u (6th generation)
  • RAM: DDR4 8GB 2133 MHz
  • SSD: SAMSUNG MZVLV256HCHP-00000

2.3. Notebook: Xiaomi Mi 13 with Waterfox (64-bit Firefox) Browser test results

Edit

This test has been made on PC with:

  • OS: Windows 10 x64
  • Program: Waterfox 56.2.12 (64-bit)
  • CPU: Intel i5-6200u (6th generation)
  • RAM: DDR4 8GB 2133 MHz
  • SSD: SAMSUNG MZVLV256HCHP-00000

2.3. Smartphone: Xiaomi Mi 5 Pro with Google Chrome Browser test results

Edit

This test has been made on phone with:

  • OS: Android 8.0.0 (MIUI Global 10.2 | Stable)
  • Program: Google Chrome
  • CPU: Qualcomm Snapdragon 820 8996
  • RAM: 3GB
  • SSD/FLASH: 60GB 
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join