배열(Array)을 벡터(Vector)로 변환하는 것을 테스트 해봤습니다. 인터넷에서 검색해보면 거의 for나 for in을 사용해서 변환을 시키더군요. 그래서 Function.apply()를 사용하면 어떨까 하고 시험해 봤는데, apply 가 압도적인 속도를 보여주고, 코드 또한 간결하네요.

아래 코드로 테스트 해보면 대충 for는 80ms, for in은 90ms, apply는 15ms 정도의 속도를 보여줍니다. Function.apply()를 가끔 사용하긴 하는데, 이렇게 빠른지는 오늘 처음 알았네요.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import flash.utils.getTimer;
 
// original array
var arr:Array = new Array();
for(var i:uint=0; i<1000000; i++){
	arr.push(i);
}
 
// vector
var vec:Vector.<int> = new Vector.<int>();
 
var n:int = getTimer();
 
// for
/*var len:uint = arr.length;
for(i=0; i<len; i++){
	vec.push(arr[i]);
}*/
 
// for in
/*var num:uint;
for each(num in arr)
{
    vec.push(num); 
}*/
 
// Function.apply
vec.push.apply(null, arr);
 
trace(getTimer() - n);
trace(vec.length);
 
Array.length is a read-write property. I should’ve know it.
I just thought it was a read-only property. I came to know it reading a copy of EAS3.0.
Array.length 속성이 리드-라이트 였네요. 이런걸 지금까지 모르고 있었다니…
당연히 Read-only일 거라고 생각하고 있었는데, EAS3.0을 보다가 알게 되었네요.
Array.lengthがread-write属性だったんですね。なぜ今まで知らなかったんだろう……
当然read-onlyだと思っていったのに、EAS3.0を読みながら分かった。

length property
length:uint [read-write]

Language Version : ActionScript 3.0
Player Version : Flash Player 9

A non-negative integer specifying the number of elements in the array. This property is automatically updated when new elements are added to the array. When you assign a value to an array element (for example, my_array[index] = value), if index is a number, and index+1 is greater than the length property, the length property is updated to index+1.

Note: If you assign a value to the length property that is shorter than the existing length, the array will be truncated.

quote from ActionScript 3.0 Language Reference

1
2
3
4
var arr:Array = new Array(0, 1, 2, 3, 4, 5, 6);
trace(arr);// output 0,1,2,3,4,5,6
arr.length = 4;
trace(arr);// output 0,1,2,3
If the newly assigned length is shorter than the existing value, items whose index is larger than the length will be removed from the array and the array will be shortened to the specified length. In some cases, it is more useful than Array.slice() or Array.splice() methods.
위와 같이 length에 현재 길이보다 작은 값을 입력하면, length 이후의 아이템들을 제거하고 배열이 입력받은 길이로 줄어들게 됩니다. 경우에 따라서는 Array.slice(), Array.splice() 보다 유용할 것 같네요.
若し、新しいlengthが現在のlengthより少ないと、それ以後の配列要素は取り去れて、その配列の長さは短くなります。時折Array.slice()やArray.splice()メソッドより便利そうです。
© 2011 Hangun's World - Blog Suffusion theme by Sayontan Sinha