發現一篇好文,介紹AS3中常見的位運算技巧的。小弟勉強翻譯一下,有錯誤還請指正。原文在這里
在AS3中位操作是非??斓模@里列出一些可以加快某些計算速度的代碼片段集合。我不會解釋什么是位運算符,也不會解釋怎么使用他們,只能告訴大家如果想清楚其中的原理這里有一篇極好的文章在gamedev.net上叫做 ‘Bitwise Operation in C' .
如果你知道任何下邊沒有列出來的不錯的技巧,請留下個評論或者給我發個郵件。所有這些都是基于AS3的
[b]左位移幾就相當于乘以2的幾次方[/b]( Left bit shifting to multiply by any power of two )
大約快了300%
[code]
x = x * 2;
x = x * 64;
//相當于:
x = x << 1;
x = x << 6;
[/code]
[b]右位移幾就相當于除以2的幾次方[/b](Right bit shifting to divide by any power of two)
大約快了350%
[code]
x = x / 2;
x = x / 64;
//相當于:
x = x >> 1;
x = x >> 6;
[/code]
[b]Number 到 integer(整數)轉換[/b]
在AS3中使用int(x)快了10% 。盡管如此位操作版本在AS2中工作的更好
[code]
x = int(1.232)
//相當于:
x = 1.232 >> 0;
[/code]
[b]提取顏色組成成分[/b]
不完全是個技巧,是正常的方法 (Not really a trick, but the regular way of extracting values using bit masking and shifting.)
[code]
//24bit
var color:uint = 0x336699;
var r:uint = color >> 16;
var g:uint = color >> 8 & 0xFF;
var b:uint = color & 0xFF;
//32bit
var color:uint = 0xff336699;
var a:uint = color >>> 24;
var r:uint = color >>> 16 & 0xFF;
var g:uint = color >>> 8 & 0xFF;
var b:uint = color & 0xFF;
[/code]
[b]合并顏色組成成分[/b]
替換值到正確位置并組合他們 (‘Shift up’ the values into the correct position and combine them.)
[code]
//24bit
var r:uint = 0x33;
var g:uint = 0x66;
var b:uint = 0x99;
var color:uint = r << 16 | g << 8 | b;
//32bit
var a:uint = 0xff;
var r:uint = 0x33;
var g:uint = 0x66;
var b:uint = 0x99;
var color:uint = a << 24 | r << 16 | g << 8 | b;
[/code]
[b]使用異或運算交換整數而不需要用臨時變量[/b]
很可愛的技巧, 在本頁頂端的鏈接里有詳細的解釋 ,這里快了 20%
[code]
var t:int = a;
a = b;
b = t;
//相當于:
a ^= b;
b ^= a;
a ^= b;
[/code]
[b]自增/自減(Increment/decrement)[b]
這個比以前的慢不少,但卻是個模糊你代碼的好方法;-)
[code]
i = -~i; // i++
i = ~-i; // i--
[/code]
[b]取反[/b](Sign flipping using NOT or XOR)
另人奇怪的是這個居然快了300%!
[code]
i = -i;
//相當于:
i = ~i + 1;
//或者
i = (i ^ -1) + 1;
[/code]
[b]使用bitwise AND快速取模[/b] (Fast modulo operation using bitwise AND)
如果除數是2的次方,取模操作可以這樣做:
模數= 分子 & (除數 - 1);
這里大約快了600%
[code]
x = 131 % 4;
//相當于:
x = 131 & (4 - 1);
[/code]
[b]檢查是否為偶數[/b](Check if an integer is even/uneven using bitwise AND)
這里快了 600%
[code]
isEven = (i % 2) == 0;
//相當于:
isEven = (i & 1) == 0;
[/code]
[b]絕對值[/b]
忘記 Math.abs()吧 (Forget Math.abs() for time critical code.)
version 1 比 Math.abs() 快了2500% ,version 2 居然比 version 1 又快了20% !
[code]
//version 1
i = x < 0 ? -x : x;
//version 2
i = (x ^ (x >> 31)) - (x >> 31);
[/code]
posted on 2008-07-29 14:14
姜大叔 閱讀(311)
評論(0) 編輯 收藏 所屬分類:
Flash/Flex