正则表达式或异常处理? [英] Regex or Exception Handling?

查看:28
本文介绍了正则表达式或异常处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下哪一项是检查字符串是否为浮点数的更好做法?

Which one of the following is a better practice to check if a string is float?

try{
 Double.parseDouble(strVal);
}catch(NumberFormatException e){
 //My Logic
}

if(!strVal.matches("[-+]?\\d*\\.?\\d+")){
 //My Logic
}

在性能、维护性和可读性方面?

In terms of performace, maintainence and readability?

是的,我想知道哪种编码习惯是好的?

And yeah, I would like to know which one is good coding practice?

推荐答案

  1. 性能:异常很慢,基于异常的逻辑也是如此,所以第二个会更快.
  2. 维护/可靠性:第一个非常清晰,将随着 Java 框架的更新保持更新.

话虽如此,我个人更喜欢第一个.性能是您希望在架构、数据结构设计等中作为一个整体考虑的事情,而不是逐行考虑.衡量性能并优化实际缓慢的部分,而不是您认为可能缓慢的部分.

That being said, I would personally prefer the first. Performance is something you want to consider as a whole in your architecture, your data structure design, etc. not line by line. Measure for performance and optimize what is actually slow, not what you think might be slow.

这篇关于正则表达式或异常处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆