Checking for string contents? string Length Vs Empty String

前端 未结 13 900
野趣味
野趣味 2020-12-17 10:14

Which is more efficient for the compiler and the best practice for checking whether a string is blank?

  1. Checking whether the length of the string == 0
13条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-17 10:50

    In languages that use C-style (null-terminated) strings, comparing to "" will be faster. That's an O(1) operation, while taking the length of a C-style string is O(n).

    In languages that store length as part of the string object (C#, Java, ...) checking the length is also O(1). In this case, directly checking the length is faster, because it avoids the overhead of constructing the new empty string.

提交回复
热议问题