發(fā)現(xiàn)一篇好文,介紹AS3中常見(jiàn)的位運(yùn)算技巧的。小弟勉強(qiáng)翻譯一下,有錯(cuò)誤還請(qǐng)指正。原文在這里
在AS3中位操作是非常快的,這里列出一些可以加快某些計(jì)算速度的代碼片段集合。我不會(huì)解釋什么是位運(yùn)算符,也不會(huì)解釋怎么使用他們,只能告訴大家如果想清楚其中的原理這里有一篇極好的文章在gamedev.net上叫做 ‘Bitwise Operation in C' .
如果你知道任何下邊沒(méi)有列出來(lái)的不錯(cuò)的技巧,請(qǐng)留下個(gè)評(píng)論或者給我發(fā)個(gè)郵件。所有這些都是基于AS3的
[b]左位移幾就相當(dāng)于乘以2的幾次方[/b]( Left bit shifting to multiply by any power of two )
大約快了300%
[code]
x = x * 2;
x = x * 64;
//相當(dāng)于:
x = x << 1;
x = x << 6;
[/code]
[b]右位移幾就相當(dāng)于除以2的幾次方[/b](Right bit shifting to divide by any power of two)
大約快了350%
[code]
x = x / 2;
x = x / 64;
//相當(dāng)于:
x = x >> 1;
x = x >> 6;
[/code]
[b]Number 到 integer(整數(shù))轉(zhuǎn)換[/b]
在AS3中使用int(x)快了10% 。盡管如此位操作版本在AS2中工作的更好
[code]
x = int(1.232)
//相當(dāng)于:
x = 1.232 >> 0;
[/code]
[b]提取顏色組成成分[/b]
不完全是個(gè)技巧,是正常的方法 (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]使用異或運(yùn)算交換整數(shù)而不需要用臨時(shí)變量[/b]
很可愛(ài)的技巧, 在本頁(yè)頂端的鏈接里有詳細(xì)的解釋 ,這里快了 20%
[code]
var t:int = a;
a = b;
b = t;
//相當(dāng)于:
a ^= b;
b ^= a;
a ^= b;
[/code]
[b]自增/自減(Increment/decrement)[b]
這個(gè)比以前的慢不少,但卻是個(gè)模糊你代碼的好方法;-)
[code]
i = -~i; // i++
i = ~-i; // i--
[/code]
[b]取反[/b](Sign flipping using NOT or XOR)
另人奇怪的是這個(gè)居然快了300%!
[code]
i = -i;
//相當(dāng)于:
i = ~i + 1;
//或者
i = (i ^ -1) + 1;
[/code]
[b]使用bitwise AND快速取模[/b] (Fast modulo operation using bitwise AND)
如果除數(shù)是2的次方,取模操作可以這樣做:
模數(shù)= 分子 & (除數(shù) - 1);
這里大約快了600%
[code]
x = 131 % 4;
//相當(dāng)于:
x = 131 & (4 - 1);
[/code]
[b]檢查是否為偶數(shù)[/b](Check if an integer is even/uneven using bitwise AND)
這里快了 600%
[code]
isEven = (i % 2) == 0;
//相當(dāng)于:
isEven = (i & 1) == 0;
[/code]
[b]絕對(duì)值[/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)
評(píng)論(0) 編輯 收藏 所屬分類(lèi):
Flash/Flex