Faster Algorithm for JavaScript function call within a function

前端 未结 3 1156
野的像风
野的像风 2021-01-17 06:19

I have written a function and called another function inside but my tests show that it is not time optimized. How can I make the following code faster?

    f         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-17 07:14

    1) You can define the function sumAll outside of the function maxSum because every time you call maxSum the javascript engine is recreating a fresh new function sumAll.

    2) You can define myrange[1] as a variable in the initialiser part to avoid javascript to look for myrange[1] at each iteration.

                for (var i = myrange[0]; i <= myrange[1]; i++) {
    
                    total += array1[i];
                }
    

    become this:

                for (var i = myrange[0], len = myrange[1]; i <= len; i++) {
    
                    total += array1[i];
                }
    

提交回复
热议问题