Is arr.length = 0 better than arr = [] in javascript during resale
I'm improving the performance of an HTML5 game, while I reset some arrays to reduce garbage collection, I tend to use array.length = 0 (but I'm not sure if it works in the real world)
I ran some tests to find out the speed of these two types of reset array here
http://tinkerbin.com/hqQvp5fQ
Yes, setting length
to zero is the best solution as it truncates the existing array, but arr=[]
creates a new array and stores a reference to it in arr
. It may happen that the old array is no longer referenced and garbage collected. Hence, it arr=[]
may require additional collection and garbage collection compared to arr.length=0
.
See this for a description of the special behavior of the property length
it relies on.