문제

Looking at some pieces of code around the internet, I've noticed some authors tend to write string comparisons like

if("String"==$variable)

in PHP, or

if("String".equals(variable))

Whereas my preference is:

if(variable.equals("String"))

I realize these are effectively equal: they compare two strings for equality. But I was curious if there was an advantage to one over the other in terms of performance or something else.

Thank you for the help!

도움이 되었습니까?

해결책

One example to the approach of using an equality function or using if( constant == variable ) rather than if( variable == constant ) is that it prevents you from accidentally typoing and writing an assignment instead of a comparison, for instance:

if( s = "test" )

Will assign "test" to s, which will result in undesired behaviour which may potentially cause a hard-to-find bug. However:

if( "test" = s )

Will in most languages (that I'm aware of) result in some form of warning or compiler error, helping to avoid a bug later on.

다른 팁

With a simple int example, this prevents accidental writes of

if (a=5)

which would be a compile error if written as

if (5=a)

I sure don't know about all languages, but decent C compilers warn you about if (a=b). Perhaps whatever language your question is written in doesn't have such a feature, so to be able to generate an error in such a case, they have reverted the order of the comparison arguments.

Yoda conditions call these some.

The kind of syntaxis a language uses has nothing to do with efficiency. It is all about how the comparison algorithm works.

In the examples you mentioned, this:

if("String".equals(variable))

and this:

if(variable.equals("String"))

would be exactly the same, because the expression "String" will be treated as a String variable.

Languages that provide a comparison method for Strings, will use the fastest method so you shouldn't care about it, unless you want to implement the method yourself ;)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top