`

大数据量下的trycatch 损耗大,还是if(object!=null)损耗大

阅读更多

今天和某个同事探讨一段代码的效率

getName1 效率高还是 getName 效率高。

我说getName1比较好,getName效率会比较差。因为有try catch性能会差。他说如果大多数情况下我test能确认不为空,那么是不是可以选getName。随后我做一下实验

 

java version "1.8.0_66"

Java(TM) SE Runtime Environment (build 1.8.0_66-b18)

Java HotSpot(TM) 64-Bit Server VM (build 25.66-b18, mixed mode)

 

public  String getName1(Test test) throws Exception{
   if(test!=null)
      return test.getName();
   else
      throw new Exception("test");

}
public  String getName(Test test) throws Exception{
   try {
      return test.getName();
   }catch (Exception e){
      throw e;
   }
        try {
//            while (index < 10) {
                long start1 = System.currentTimeMillis();
                for (int i = 0; i < 1000000000; i++) {
                    t.getName(test);
                }
                System.out.println("start1 time :" + (System.currentTimeMillis() - start1));
                long start2 = System.currentTimeMillis();

                for (int i = 0; i < 1000000000; i++) {
                    t.getName1(test);
                }

                System.out.println("start2 time :" + (System.currentTimeMillis() - start2));
//                index++;
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
用这段代码测试10次后得到的结果既然是平手。
如果还有朋友愿意测下别的jdk版本请将结果告诉我。
 }
分享到:
评论
1 楼 107192468a 2016-05-09  
将 1000000000 加大到10000000000 然后统计了10次运行的结果发现:
用if(test!=null)
尽然平均会比try{} catch {} 这种写法多上2000ms。
但是一旦真的出异常了,那么结局就是想反。代码如下
public class A {
	private static class Test {
		private String name;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

	}

	public String getName1(Test test) throws Exception {
		if (test != null)
			return test.getName();
		else
			throw new Exception("test");

	}

	public String getName(Test test) throws Exception {
		try {
			return test.getName();
		} catch (Exception e) {
			throw e;
		}
	}

	public static void main(String[] args) {
		A t = new A();
		Test test = new Test();
		test.setName("123123");

		long start1 = System.currentTimeMillis();

		for (long i = 0; i < 10000000000L; i++) {
			
			try {
				if (i == 1000000000L){
					test = null;
				}
				if (i==1000000001L){
					test=new Test();
					test.setName("123123");
				}
				t.getName(test);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		System.out.println("start1 time :" + (System.currentTimeMillis() - start1));
		long start2 = System.currentTimeMillis();

		for (long i = 0; i < 10000000000L; i++) {
			try {
				if (i == 1000000000L){
					test = null;
				}
				if (i==1000000001L){
					test=new Test();
					test.setName("123123");
				}
				t.getName1(test);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		System.out.println("start2 time :" + (System.currentTimeMillis() - start2));
	}

}


java.lang.NullPointerException
at read.util.A.getName(A.java:27)
at read.util.A.main(A.java:50)
start1 time :13986
java.lang.Exception: test
at read.util.A.getName1(A.java:21)
at read.util.A.main(A.java:68)
start2 time :11423

如果代码有错,或者思路有错,请纠正

相关推荐

    java数据库封装类

    = null) { pstmt = conn.prepareStatement(sql); } } catch (SQLException e) { e.printStackTrace(); } return pstmt; } public static PreparedStatement prepare(Connection conn, String ...

    Java连接sqlserver2005

    = null) { rs.close(); rs = null; } if(stmt !=null){ stmt.close(); stmt = null; } if(conn != null){ conn.close(); conn = null; }...

    连接数据库

    = null) { rs.close(); } } catch (SQLException e) { System.out.println("rs关闭异常!"); }finally{ try { if (conn!= null) { conn.close(); } } catch (SQLException e) { System.out.println(...

    文件内容读取类

    = null) {//使用readLine方法,一次读一行 wordList.add(s.trim()); } } catch (Exception e) { Logger.getLogger(FileUtil.class).info(e); return Collections.emptyList(); } finally { try { if (br !=...

    asp.net实现购物车的几种方法

    try { if (Session["logon"]!...=null||Request.Params["productID"]!="") { AddProID=Request["productID"]; UpdateShoppingCart(); Caculator(); } }// 在此处放置用户代码以初始化页面 }

    jspblog项目

    =null){ if(isFirst){ firstLine=tmp; isFirst=false; } index=tmp.indexOf("finename="); if(index!=-1){ String tailString = tmp.substring(index+10); if(tailString != ...

    ASP四级联动下拉菜单 (XML+Access)

    = null && m_oXMLDoc.xml != "" ) { objSelect.length = 0; aryXMLNodes = m_oXMLDoc.documentElement.selectNodes("TreeNode"); objSelect.options[0] = new Option("==全部=="); for (var i=0; i ; i++) ...

    python基础教程:嵌套字典取值.pdf

    dict) : try: value = d[code] result.append(value) except Exception as e: pass for valuedd in d.values(): if isinstance(valuedd,dict): yied_result=getdictvalue(valuedd,code) if len(yied_result) !...

    关于io的一些代码

    =null) { out.println(str); } } catch(IOException e){ System.out.println(e); } finally{ try { if(in!=null) in.close(); if(out!=null) out.close(); }catch(IOException e){ System.out.println...

    jdbc-odbc的基本操作

    = null) { rs.close(); } if (pstmt != null) { pstmt.close(); } if (cn != null) { cn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ...

    oracle大数据块添加

    = null && dt.Rows.Count != 0) { bulkCopy.WriteToServer(dt); } } catch (Exception ex) { // Log.WriteLog(err, ex); } finally { conn.Close(); if (bulkCopy != null) bulkCopy.Close(); } }

    MediaEx.zip_The Exception

    try { // create a player to play the media specified in the URL URL mediaURL = new File(“Alarm.mp3”).toURL() Player mediaPlayer = Manager.createRealizedPlayer(mediaURL) Component video = ...

    中文分词检索系统

    =null) { String b = buffer; System.out.println("开始检索关键字:"+b); buffer = URLEncoder.encode(buffer, "UTF-8"); String url = "http://s.wanfangdata.com.cn/Paper.aspx?q=" + buffer + "&f=top"; ...

    jsp 留言板

    =null) rs.close(); } catch(Exception e) { e.printStackTrace(); } try { if (stmt!=null) stmt.close(); } catch(Exception e) { e.printStackTrace(); } try { if ...

    wpf的Excel分类导出数据(Aspose)

    = null) ErrorHappened(this, new StringEventArgs("缺少有效的工作表")); return null; } Worksheet ws = wb.Worksheets[0]; string areaKey = "区域"; int areaPos = -1; // 获取区域所在列号 this.m_...

    HttpConnectionTool工具类

    =null&&header.size()&gt;0) { for (String key : header.keySet()) { httpost.setHeader(key,header.get(key)); } } List &lt;NameValuePair&gt; nvps = new ArrayList (); for (String keyItem : params...

    商品买卖 jsp版 jsp版 商品买卖 jsp版

    =null) rs.close(); } catch(Exception e) { e.printStackTrace(); } try { if (stmt!=null) stmt.close(); } catch(Exception e) { e.printStackTrace(); } try { if ...

    java中try catch的用法

    java中try catch的用法 java try catch的用法 java中 try catch的用法

    C语言模拟实现 try catch

    使用setjmp和longjmp方式模拟try catch的功能,两种方式都可以使用,setjmp的方式可以支持try catch嵌套,goto的方式不支持嵌套,但是jmpbuf的开销是比较大的,在MDK ARM下为typedef __int64 jmp_buf[48];...

    Excel POI读取封装(文件+示范代码)

    = null && endPoint != null) { sc = startPoint.split(","); ec = endPoint.split(","); startRow = Integer.parseInt(sc[1]) - 1;// 设置用户指定的开始行 endRoe = Integer.parseInt(ec[1]);// 设置用户指定...

Global site tag (gtag.js) - Google Analytics