tc39 / proposal-flatMap

proposal for flatten and flatMap on arrays
https://tc39.github.io/proposal-flatMap
214 stars 19 forks source link

Eliminate IsArray call purely for side-effects #54

Closed evilpie closed 6 years ago

evilpie commented 6 years ago

@anba already brought this up in #49. I just want to get this to your attention again and we can ask the editor if necessary.

If step 3.c.iii (Let flattenable be ? IsArray(element).) is only executed if depth > 0 is true, engines can more easily optimize the code, because it's no longer necessary to inspect every array element. (Consider the case when an array element is a revoked proxy. Calling IsArray throws for revoked proxies, so if we don't call IsArray, we can simply copy all array elements for depth = 0. With the current >algorithm we need to call IsArray even though we don't actually use the result for depth = 0.)

Because the way Array#flatten and Array#flatMap work is a bit different, an optimized version of FlattenIntoArray just for flatMap looks like this:

function FlattenIntoArray(target, source, sourceLen, start, mapperFunction, thisArg) {
    var targetIndex = start;

    for (var sourceIndex = 0; sourceIndex < sourceLen; sourceIndex++) {
        if (sourceIndex in source) {
            var element = source[sourceIndex];

            element = callContentFunction(mapperFunction, thisArg, element, sourceIndex, source);

            var flattenable = IsArray(element);

            if (flattenable) {
                var elementLen = ToLength(element.length);

                for (var elementIndex = 0; elementIndex < elementLen; elementIndex++) {
                    if (elementIndex in element) {
                        var elementElement = element[elementIndex];

                        // Only executed for its possible side-effects.
                        IsArray(elementElement);

                        _DefineDataProperty(target, targetIndex++, elementElement);
                    }
                }
            }

    ...
}
michaelficarra commented 6 years ago

Okay, it makes sense to be as lazy as possible in the case where we wouldn't want to flatten any further anyway. Previously, I was looking for some kind of consistency with always observing each element, but I don't really see that anymore. PR incoming.