This
<cfif len(x)>
Or
<cfif x NEQ "">
Which one is more efficient and readable? Function call vs comparing empty stri开发者_如何学JAVAng?
I'm with Scott on this one:
<cfif len(trim(x))>
When you assign a database element to a variable, that has a "Null" value, or a single space, it will pass just the length test, the trim fixes that.
I only use just that if I'm in my own code and I'm positive that my variables have been declared. Often I'm abroad in another programmers problem however, so my test would look like:
<cfif isdefined('x') AND len(trim(x)) gt 0>
As for readability, it's not the prettiest, but it's the most thorough.
I use:
if(len("String"));
I think the code is much cleaner and as they like to say "expressive". With this syntax what you are saying with the code is "if this string has a length" do this where with the opposite your code is "saying if the length of the string is a blank string do this".
I also use ColdFusions loose boolean values for lots of things like in addition:
if(a + b){
...
}
Personally, I typically use:
len( trim( x ) )
Ryan's on the money and rightfully has the accepted answer.
The consideration I have in situations like this is that positively-phrased expressions are slightly easier to get one's brain around than negative ones, so as far as clarity goes: using len()
is better than a negative comparison to an empty string.
Also from a pragmatic point of you, you're most probably wanting to know if you have a string with length, not that the string happens to not be an empty string (if you see the slight semantic difference), so the len()
approach will more closely match your actual requirements.
As for doing a trim()
: unless it's coming from user input and it's important that whitespace padding is removed, I would not do this. I am a firm believer in "garbage in, garbage out". It's also second-guessing the intent of the data, and I deeply dislike code that doesn't simply do precisely what it's told, no more, and no less.
There are absolutely no real-world considerations relating to performance here, so don't worry about that sort of thing, instead focus on what makes the most readable code that does the job at hand.
From what I remember, len(x) or rather len(trim(x)) is faster than x neq ""
精彩评论