比Math類庫abs()方法性能更高的取絕對值方法介紹
Math.abs()的實(shí)現(xiàn)源碼
通過三目運(yùn)算符判斷a是否小于0來實(shí)現(xiàn)
/** * Returns the absolute value of an {@code int} value. * If the argument is not negative, the argument is returned. * If the argument is negative, the negation of the argument is returned. * * <p>Note that if the argument is equal to the value of * {@link Integer#MIN_VALUE}, the most negative representable * {@code int} value, the result is that same value, which is * negative. * * @param a the argument whose absolute value is to be determined * @return the absolute value of the argument. */ public static int abs(int a) { return (a < 0) ? -a : a; }
如果換種方式,性能會(huì)有20%左右的提升
代碼如下
/** * Created by 譚健 2017/8/13. 12:47. * All Rights Reserved * * int 是 32 位數(shù)據(jù) * int 類型的任何正數(shù)右移31位 = 0,任何負(fù)數(shù)右移31位 = 1 * 溢出 31 位截?cái)?,空?31 位補(bǔ)1,得到-1 * a>>31 可以得到該數(shù)的符號(hào)位 + 還是 - * 如果 a>>31 + ,那么 a ^ 0 = a ,如果 a>>31 - ,那么 a ^ -1 翻轉(zhuǎn) a 的二進(jìn)制 * * @param a int a * @return a 的絕對值 */ public static int abs(int a){ return (a^(a>>31))-(a>>31); }
奇數(shù)偶數(shù)的判斷
/** * 一般普遍采用 n % 2 == 0 的方式 * 但是如果換成位運(yùn)算方式,效率會(huì)比前者好很多 * * 在二進(jìn)制中,末位為 0 必然是偶數(shù),否則是奇數(shù),并且不論正負(fù) * 所以,是什么數(shù),看看末位就行了 * * @param a long a * @return 如果是奇數(shù),返回true,否則返回false */ public static boolean isOdd(long a){ return (a & 1) == 1; }
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對我們的支持。
上一篇:C#ComboBox控件“設(shè)置 DataSource 屬性后無法修改項(xiàng)集合”的解決方法
欄 目:C#教程
本文標(biāo)題:比Math類庫abs()方法性能更高的取絕對值方法介紹
本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/4787.html
您可能感興趣的文章
- 01-10C#讀取Excel的三種方式以及比較分析
- 01-10C#中比較常用的DateTime結(jié)構(gòu)的使用方法
- 01-10C#比較二個(gè)數(shù)組并找出相同或不同元素的方法
- 01-10簡單對比C#程序中的單線程與多線程設(shè)計(jì)
- 01-10C# 判斷字符為空的6種方法的效率實(shí)測對比
- 01-10淺析C#中StringBuilder類的高效及與String的對比
- 01-10關(guān)于C# Math 處理奇進(jìn)偶不進(jìn)的實(shí)現(xiàn)代碼
- 01-10C# 字符串string和內(nèi)存流MemoryStream及比特?cái)?shù)組byte[]之間相互轉(zhuǎn)換
- 01-10C#實(shí)現(xiàn)的一款比較美觀的驗(yàn)證碼完整實(shí)例
- 01-10C#中數(shù)組Array,ArrayList,泛型List詳細(xì)對比


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻 器左下角滾動(dòng)新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 08-05織夢dedecms什么時(shí)候用欄目交叉功能?
- 04-02jquery與jsp,用jquery
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10C#中split用法實(shí)例總結(jié)
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 01-10使用C語言求解撲克牌的順子及n個(gè)骰子
- 01-11ajax實(shí)現(xiàn)頁面的局部加載
- 01-10delphi制作wav文件的方法
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改