1

Possible Duplicate:
How do you performance test JavaScript code?

I am currently trying to learn some JavaScript using js-assessment, which can be found here: https://github.com/rmurphey/js-assessment.

I have written the following code, which let's you find duplicates in an array:

function duplicatesInArray(arr) {
    var test;
    var res = [];

    for (var i = 0; arr[i]; i++) {
        test = arr[i];

        for (var j = i + 1 ; arr[j]; j++) {
            if(arr[j] === test) {
            res.push(arr[j]);
            break;
            }
        }
    }

    return res;
}

Which works fine, but here's an anwser I've found on github (it works too):

function anotherDuplicatesInArray(arr) {
    var seen = {};
    var dupes = [];

    for (var i = 0, len = arr.length; i < len; i++) {
        seen[arr[i]] = seen[arr[i]] ? seen[arr[i]] + 1 : 1;
    }

    for (var item in seen) {
        if (seen.hasOwnProperty(item) && seen[item] > 1) {
            dupes.push(item);
        }
    }

    return dupes;
}

My question is: how can I test which code is better?

4

0 回答 0