Overload vs Separate

Benchmark created on


Setup

// Single overloaded function approach
function drawImageOverloaded(image, x, y, width, height, srcX, srcY, srcWidth, srcHeight) {
    if (arguments.length === 3) {
        // drawImage(image, x, y)
        return `Drawing at ${x},${y} with default size`;
    } else if (arguments.length === 5) {
        // drawImage(image, x, y, width, height)
        return `Drawing at ${x},${y} with size ${width}x${height}`;
    } else if (arguments.length === 9) {
        // drawImage(image, x, y, width, height, srcX, srcY, srcWidth, srcHeight)
        return `Drawing from ${srcX},${srcY} (${srcWidth}x${srcHeight}) to ${x},${y} (${width}x${height})`;
    }
    throw new Error('Invalid number of arguments');
}

// Multiple specialized functions approach
function drawImageXY(image, x, y) {
    return `Drawing at ${x},${y} with default size`;
}

function drawImageXYWH(image, x, y, width, height) {
    return `Drawing at ${x},${y} with size ${width}x${height}`;
}

function drawImageFull(image, x, y, width, height, srcX, srcY, srcWidth, srcHeight) {
    return `Drawing from ${srcX},${srcY} (${srcWidth}x${srcHeight}) to ${x},${y} (${width}x${height})`;
}

const testImage = {};
const testArgs = {
    simple: [testImage, 10, 20],
    medium: [testImage, 10, 20, 100, 50],
    complex: [testImage, 10, 20, 100, 50, 5, 5, 90, 40]
};

Test runner

Ready to run.

Testing in
TestOps/sec
Overloaded
drawImageOverloaded.apply(null, testArgs.simple);
drawImageOverloaded.apply(null, testArgs.medium);
drawImageOverloaded.apply(null, testArgs.complex);
ready
Separate
drawImageXY.apply(null, testArgs.simple);
drawImageXYWH.apply(null, testArgs.medium);
drawImageFull.apply(null, testArgs.complex);
ready

Revisions

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