C#和java的異常處理效能對比

來源:互聯網
上載者:User

剛剛接觸C#,據說C#的異常處理很耗費效能。

於是來做個測試。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;namespace ConsoleApplication2{    class Program    {        static void Main(string[] args)        {                        Stopwatch w = new Stopwatch();            w.Start();            int a =10;            for (int i = 0; i <= 1000; i++)            {                Int32.TryParse("a", out a);            }                        w.Stop();            Console.WriteLine(w.ElapsedMilliseconds);            w.Reset();            w.Start();            for (int i = 0; i <= 1000; i++)            {                try                {                    Int32.Parse(null);                }                catch (Exception e)                {                }            }            w.Stop();            Console.WriteLine(w.ElapsedMilliseconds);            Console.Read();        }    }}

輸入的結果為:

0

6780

差距可真夠大的。看來C#中使用 TryParse還是很有必要的!

再來看看java的。同樣的代碼:

public class Test {public static void main(String[] args) {long start = System.currentTimeMillis();for(int i=0; i<1000; i++){try{Integer.parseInt(null);}catch(Exception e){}}System.out.println(System.currentTimeMillis()-start);}}

輸出結果為:

2


差距也夠大的!看來薑還是老的辣啊,微軟最佳化的還不夠……

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.