Skip to content

Performance: in Cast.compare, check === first #2570

Open
@apple502j

Description

@apple502j

By checking v1 === v2 first in Cast.compare, performance can be boosted. According to my test, this should not change the behavior of Cast.compare.

    static compare (v1, v2) {
        // If v1 === v2, it should be v1 = v2 on Scratch
        if (v1 === v2) return 0;
        // Handle the special case of Infinity
        let n1 = Number(v1);
        let n2 = Number(v2);
        if (
            (n1 === Infinity && n2 === Infinity) ||
            (n1 === -Infinity && n2 === -Infinity)
        ) {
            return 0;
        }
        if (n1 === 0 && Cast.isWhiteSpace(v1)) {
            n1 = NaN;
        } else if (n2 === 0 && Cast.isWhiteSpace(v2)) {
            n2 = NaN;
        }
        if (isNaN(n1) || isNaN(n2)) {
            // At least one argument can't be converted to a number.
            // Scratch compares strings as case insensitive.
            const s1 = String(v1).toLowerCase();
            const s2 = String(v2).toLowerCase();
            if (s1 < s2) {
                return -1;
            } else if (s1 > s2) {
                return 1;
            }
            return 0;
        }
        // Compare as numbers.
        return n1 - n2;
    }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions