test 2 functions (v2)

Revision 2 of this benchmark created on


Preparation HTML

<script src="
https://cdn.jsdelivr.net/npm/@faker-js/faker@10.1.0/dist/index.min.js
"></script>

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++
    }
    
    /*const formattedSize = new Intl.NumberFormat('en', { minimumFractionDigits: 0, maximumFractionDigits: 2 })
        .format(value)*/

    return value.toFixed(2) + ' ' + units[exponent]
}

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.toFixed(2) + ' ' + units[exponent]
  }
  
  
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.