dongwei5740 2011-12-24 07:07
浏览 15

哪个代码更有效?

I was wondering which code is more effective, meaning faster & reliable. When I have my client post data into my website, I don't allow them to use anything else other than Alphanumeric characters because there's no need for others. My question was, would an exception be faster and more reliable for this? Or should I stay away from exceptions in this purpose? Here's my code.

Normal Way -

function checkStr ($str)
{
  if (preg_match('/[^0-9a-zA-Z]/', $str) > 0))
  {
     return false;
  }
  else
  {
     return true;
  }
}
if (checkStr($_POST['field']) == true)
{
  //continue
}
else
{
  echo "Invalid characters";
}

Exception -

function checkStr ($str)
{
    if (preg_match('/[^0-9a-zA-Z]/', $str) > 0)
    {
        throw new Exception('Invalid characters');
    }
    return true;
}

    try
    {
        checkStr($_POST['field']);

        //no exception, continue with code 
    }

    catch (Exception $e)
    {
      echo $e->getMessage();

    }
}
  • 写回答

2条回答 默认 最新

  • duannuo4620 2011-12-24 07:15
    关注

    Exceptions have more overhead associated with them than normal program flow control features (if, else, elseif, etc), so purely from that point of view the first option is faster. Exceptions are tricky things, and because they're a relatively new addition to PHP people tend to overuse them. Normally, I try to only throw exceptions when the circumstances that have occured in the code are exceptional.

    For example, if I have a function where the valid inputs are the integers 1-100, then I'd have it return true for an input of 40, false for an input of 493, and throw an exception for an input of "kumquat".

    BTW, you can write the first version of your function in a single line:

    function checkStr ($str)
    {
        return (preg_match('/[^0-9a-zA-Z]/', $str) > 0));
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制