我需要检查传递的变量是否为字符串类型,并且它不是空的。我有以下功能:
function isNonEmptyStr($var)
{
if(isset($var)) {
if(is_string($var)) {
if(strlen($var) > 0) {
return true;
}
}
}
return false;
}
我期望的结果:
echo(isNonEmptyStr(''));// false
echo(isNonEmptyStr(' '));// true
echo(isNonEmptyStr('a'));// true
echo(isNonEmptyStr('1'));// true
echo(isNonEmptyStr(1));// false
echo(isNonEmptyStr(0));// false
echo(isNonEmptyStr(0.0));// false
echo(isNonEmptyStr(0.1));// false
echo(isNonEmptyStr(array()));// false
echo(isNonEmptyStr(new myObj()));// false
echo(isNonEmptyStr(true));// false
echo(isNonEmptyStr(false));// false
echo(isNonEmptyStr(null));// false
该功能工作正常。
我的问题:有没有办法在不影响结果的情况下提高功能性能?
我说的是“微优化”(我经常使用此功能)。
编辑:
对于那些在问:
echo(isNonEmptyStr(0));// should return false, because it's not a string
echo(isNonEmptyStr(1));// should return false, because it's not a string
echo(isNonEmptyStr('0'));// should return true, because it's a non-empty string
echo(isNonEmptyStr('1'));// should return true, because it's a non-empty string
注意:非空字符串=字符串,如果使用strlen()函数进行测试,它将返回> 0
这是一个简单的基准测试脚本,您可以对其进行修改以查看最有效的方法。我只是尝试了同一件事的几种变体,第一个是一点点最快的,但基本上都是一样的。而且,实际上没有一种更简单的方法可以让您编写它。
此外,$val === ''
它的速度比略快empty($val)
,而且对您的要求更严格。
另外,由于这基本上是一个线性函数,所以为什么不减少使其成为函数并is_string($val) && $val !== ''
直接调用的开销。它并没有太大的区别,但是它在数百万次迭代中引人注目,但是我怀疑此过程是否会成为您任何代码中的主要瓶颈...
function is_non_empty_string_1($val)
{
return is_string($val) && $val !== '';
}
function is_non_empty_string_2($val)
{
return gettype($val) === 'string' && $val !== '';
}
function is_non_empty_string_3($val)
{
switch (true) {
case !is_string($val): return false;
case $val === '': return false;
}
return true;
}
$values = array('', '1', new stdClass(), 1, 2, 3, 999, array(), array());
$runs = 2000000;
function benchmark($test, $values, $runs, $func)
{
$time = time();
for ($i = 0; $i < $runs; $i++) {
foreach ($values as $v) {
$func($v);
}
}
echo $test . '. ' . (time() - $time) . PHP_EOL;
}
benchmark(1, $values, $runs, 'is_non_empty_string_1');
benchmark(2, $values, $runs, 'is_non_empty_string_2');
benchmark(3, $values, $runs, 'is_non_empty_string_3');
结果:
1. 5
2. 6
3. 6
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句