JavaScript loop with anonymous function performance

I have this simple code (the purpose of this code is irrelevant)

const filter = function (object, subject, match) {
    const result = [];

    let index = 0;

    for (let i = 0; i < object.length; i++) {
        let existingIndex = -1;

        for (let j = index; j < subject.length; j++) {
            if (match(object[i], subject[j])) {
                existingIndex = j;
                break;
            }
        }

        if (existingIndex === -1) {
            result.push(object[i]);
        } else {
            index = existingIndex;
        }
    }

    return result;
};

const subjectArray = Array.from({ length: 199999 }).map((_, i) => i);
const objectArray1 = Array.from({ length: 99999 }).map((_, i) => i);
const objectArray2 = Array.from({ length: objectArray1.length }).map(() => -1);

const match = (item, entry) => item === entry;

function f1() {
    console.time("f1");

    filter(subjectArray, objectArray1, (item, entry) => item === entry);

    console.timeEnd("f1");
}

function f2() {
    console.time("f2");

    filter(subjectArray, objectArray2, (item, entry) => item === entry);

    console.timeEnd("f2");
}

f1();
f2();

When I run the code, it takes a lot of time. But when I change

filter(subjectArray, objectArray2, (item, entry) => item === entry)

to

filter(subjectArray, objectArray2, match)

the execution is much faster. Can somebody please explain to me, what is happening during the execution and what is the difference?

>Solution :

when you use an anonymous arrow function, it’s treated as a new function each time it’s encountered, whereas when you use a named function, the JavaScript engine can recognize and optimize the function as it’s reused.

in your code, the first case uses an anonymous arrow function:

filter(subjectArray, objectArray1, (item, entry) => item === entry);

in this case, the JavaScript engine sees a new anonymous function each time it’s executed. Since the engine doesn’t know if this function will remain the same or not, it doesn’t optimize it as much as it could.

On the other hand, when you use the named function match:

filter(subjectArray, objectArray2, match);

The JavaScript engine recognizes the match function as the same function each time it’s executed. This allows the engine to optimize the function call better, leading to improved performance. The performance difference is more noticeable in your code because the filter function has nested loops that result in many function calls. With more iterations, the optimization benefits of using a named function become more evident. So final conclusion is when using a callback function repeatedly, it’s a good idea to use a named function instead of an anonymous function to take advantage of JavaScript engine optimizations.

Leave a Reply