test 2 functions

Benchmark created on


Preparation HTML

<script src="https://esm.sh/@faker-js/faker"/>

Setup


function formatNumberAsFileSize1 (value) {
    const units = ['bytes', 'Kb', 'Mb', 'Gb']
    if (!value) return '-'
    let iterations = 0
    while (value >= 1024 && iterations < units.length - 1) {
        value = value / 1024
        iterations++
    }
    return value
}

function formatNumberAsFileSize2 (value) {
    if (!value) return '-'

    const units = ['bytes', 'Kb', 'Mb', 'Gb']
    const exponent = Math.min(Math.floor(Math.log2(value) / 10), units.length - 1)
    const size = value / Math.pow(1024, exponent)

    return size
  }
  
  
var data = [...Array(1000).map(() => faker.number.int(Math.pow(1024, Math.random() * 4))]

Test runner

Ready to run.

Testing in
TestOps/sec
fn 1
data.map(i => formatNumberAsFileSize1(i))
ready
fn 2
data.map(i => formatNumberAsFileSize2(i))
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.