benchmark java_Benchmark of Java Try/Catch Block

I know that going into a catch block has some significance cost when executing a program, however, I was wondering if entering a try{} block also had any impact so I started looking for an answer in google with many opinions, but no benchmarking at all. Some answers I found were:

Java try/catch performance, is it recommended to keep what is inside the try clause to a minimum?

Try Catch Performance Java

Java try catch blocks

However they didn\'t answer my question with facts, so I decided to try it for myself.

Here\'s what I did. I have a csv file with this format:

host;ip;number;date;status;email;uid;name;lastname;promo_code;

where everything after status is optional and will not even have the corresponding ; , so when parsing a validation has to be done to see if the value is there, here\'s where the try/catch issue came to my mind.

The current code that I inherited in my company does this:

StringTokenizer st=new StringTokenizer(line,\";\");

String host = st.nextToken();

String ip = st.nextToken();

String number = st.nextToken();

String date = st.nextToken();

String status = st.nextToken();

String email = \"\";

try{

email = st.nextToken();

}catch(NoSuchElementException e){

email = \"\";

}

and it repeats what it\'s done for email with uid, name, lastname and promo_code.

and I changed everything to:

if(st.hasMoreTokens()){

email = st.nextToken();

}

and in fact it performs faster. When parsing a file that doesn\'t have the optional columns. Here are the average times:

--- Trying:122 milliseconds

--- Checking:33 milliseconds

however, here\'s what confused me and the reason I\'m asking: When running the example with values for the optional columns in all 8000 lines of the CSV, the if() version still performs better than the try/catch version, so my question is

Does really the try block does not have any performance impact on my code?

The average times for this example are:

--- Trying:105 milliseconds

--- Checking:43 milliseconds

Can somebody explain what\'s going on here?

Thanks a lot

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值