lodash random vs custom random number 1024

Benchmark created by jerry on


Preparation HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>

Setup

function isBoolean(value) {
        return typeof value === "boolean";
    }
    function random(min, max, float) {
        switch(arguments.length) {
            case 2:
                if(isBoolean(max)) {
                    float = max;
                }
                else {
                    break;
                }
                /* falls through */
            case 1:
                max = min;
                min = 0;
        }
        
        var result,
            rand = Math.random();
        
        if(!min && !max) {
            return rand;
        }
        
        if(min % 1 !== 0 || max % 1 !== 0) {
            float = true;
        }
        
        result = rand * (max - min) + min;
        
        return float ? result : parseInt(result);
    }
    
    function shuffle(array) {
        var index, randInt,
            length = array.length,
            result = new Array(length);
     
        for(index = 0; index < length; ++index) {
            randInt = parseInt(Math.random() * index);
    
            if(index !== randInt) {
                result[index] = result[randInt];
            }
    
            result[randInt] = array[index];
        }
    
        return result;
    }
    function shuffleRaw(array) {
        var index, randInt,
            length = array.length,
            result = new Array(length);
     
        for(index = 0; index < length; ++index) {
            randInt = parseInt(random() * index);
    
            if(index !== randInt) {
                result[index] = result[randInt];
            }
    
            result[randInt] = array[index];
        }
    
        return result;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
lodash
_.random(0, 5);
// → an integer between 0 and 5

_.random(5);
// → also an integer between 0 and 5

_.random(5, true);
// → a floating-point number between 0 and 5

_.random(1.2, 5.2);
// → a floating-point number between 1.2 and 5.2
ready
custom
random(0, 5);
// → an integer between 0 and 5

random(5);
// → also an integer between 0 and 5

random(5, true);
// → a floating-point number between 0 and 5

random(1.2, 5.2);
// → a floating-point number between 1.2 and 5.2
ready
lodash shuffle
_.shuffle([1, 2, 3, 4, 5, 6]);
ready
custom shuffle
shuffle([1, 2, 3, 4, 5, 6]);
ready
custom shuffle raw
shuffleRaw([1, 2, 3, 4, 5, 6]);
ready

Revisions

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

  • Revision 1: published by jerry on