Interesting. Good to know. Here’s what I got:
function timeJoin(){
var start = new Date();
var i=-1;
var len = 10000000;
var arr = [];
while(++i<len)
{
arr[i] = "a";
}
var str = arr.join("");
var end = new Date();
console.log(end.getTime()-start.getTime());
};
function timePush(){
var start = new Date();
var i=-1;
var len = 10000000;
var arr = [];
while(++i<len)
{
arr.push("a");
}
var str = arr.join("");
var end = new Date();
console.log(end.getTime()-start.getTime());
};
Chrome:
timeJoin()
822
timePush()
979
Firefox:
timeJoin()
184
timePush()
303
Not what I’d call “terrible” (at least for short strings), but indexed
assignment is definitely faster.
On Jul 26, 2016, at 8:28 PM, Josh Tynjala <[email protected]> wrote:
> Yeah, push() is terribly bad for performance because of the GC overhead
> from the ...rest Array. In Starling and Feathers, we always try to avoid
> push() whenever possible. We usually use bracket syntax instead:
>
> array[array.length] = newValue;
>
> In loops, it's possible to use a local integer counter instead of checking
> the length property every time.
>
> counter = 0; //or counter = array.length, if it isn't empty
> for(...)
> {
> array[counter] = newValue;
> counter++;
> }
>
> - Josh
>
>
> On Tue, Jul 26, 2016 at 10:15 AM, Alex Harui <[email protected]> wrote:
>
>>
>>
>> On 7/26/16, 1:40 AM, "Harbs" <[email protected]> wrote:
>>
>>> I noticed a couple of things:
>>> 1. There’s lots of String(val) casts in FlexJS code. This practice is
>>> considered “bad” practice in Javascript where implicit conversion is
>>> generally quicker. So in a case where a number can be converted
>>> implicitly, the cast should be completely skipped and even when a number
>>> needs to be converted to a string, “” + val is more efficient than
>>> String(val). This is especially true in FlexJS where (I believe) such
>>> code will result in org.apache.flex.Language.as(val,”String”).
>>
>> I'm not seeing this. What source code is generating String(val) calls?
>> Regarding optimization, do we know if GCC will do this ("" + val)
>> optimization for us?
>>
>> In general, there is a big TODO around type conversions.
>>
>>>
>>> 2. String concatenation: I’m not sure how much of an issue this is in
>>> current browsers, but using aray.join() to build a string was MUCH faster
>>> than building strings using the plus operator. For longer strings the
>>> difference was dramatic.
>>
>> If I understood this, it would be hard for the compiler to generate the
>> right code for all browsers. You could create a StringBuilder class that
>> checks platforms and runs different code at runtime.
>>
>> FWIW, Flex UIDUtils uses ByteArray because, IIRC, while array.join() might
>> be fast, the array.push() is horribly slow and generates a lot of GC
>> activity.
>>
>> HTH,
>> -Alex
>>
>>