JS: For loop vs Array.indexOf (v190)

Revision 190 of this benchmark created on


Description

Testing speed of a standard for loop vs. Array.indexOf.

Preparation HTML

<script>
 function m1(obj, callback, deep) {
                var obj_keys = Object.keys(obj),
                        obj_keys_len = obj_keys.length,
                        new_obj = {},
                        value,
                        key,
                        i;

                for (i = 0; i < obj_keys_len; i += 1) {
                        key = obj_keys[i];
                        value = obj[key];

                        if (deep && (typeof value === 'object' && value != null)) {
                                new_obj[key] = m1(value, callback, true);
                        }
                        else {
                                new_obj[key] = callback(value);
                        }
                }

                return new_obj;
        }
        
function m2(obj, callback, deep) {
                var value,
                        new_obj = {};

                Object.keys(obj).map(function (key) {
                        value = obj[key];

                        if (deep && (typeof value === 'object' && value != null)) {
                                new_obj[key] = m2(value, callback, true);
                        }
                        else {
                                new_obj[key] = callback(value);
                        }
                });

                return new_obj;
        };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
For loop === first
m1({name: 'jack', age: 23, student: {class_: 'nobody knows', year: 1111}}, function (e) { return e + ' hello world'; }, true)
ready
For loop in first
m2({name: 'jack', age: 23, student: {class_: 'nobody knows', year: 1111}}, function (e) { return e + ' hello world'; }, true)
ready

Revisions

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