简体   繁体   English

在 Java 中检查字符串不为空且不为空的最佳方法是什么?

[英]What is the best way to check string not null and not empty in Java?

我认为!StringUtils.isEmpty(string)string != null && string.length()!=0哪个对性能更好??

I would prefer string != null && !string.isEmpty() .我更喜欢string != null && !string.isEmpty() The intent is clear and why rely on an external library for such a simple thing.意图很明确,为什么要依赖外部库来完成这么简单的事情。

There's no relevant performance difference.没有相关的性能差异。 When the code gets used a lot, the utility method gets inlined and then it's exactly the same.当代码被大量使用时,实用程序方法被内联,然后它完全相同。 When it doesn't get used, then nobody cares.当它不使用时,没有人在乎。

Performance is sometimes important, but such trivialities have no impact.性能有时很重要,但这些琐碎的事情没有影响。 Learn Java benchmarking (JMH) before you even start thinking about optimizations.在开始考虑优化之前学习 Java 基准测试 (JMH)。

In case you already use Apache Commons, then use their utility methods.如果您已经使用 Apache Commons,请使用它们的实用方法。 If you don't than don't bring the library in just because of such a triviality.如果你不这样做,就不要因为这样的琐事而把图书馆带进来。 OTOH there are many other useful things in the library (FWIW I started with some trivial methods from Guava and now I use a substantial portion of it). OTOH 库中还有许多其他有用的东西(FWIW 我从 Guava 的一些琐碎方法开始,现在我使用了其中的很大一部分)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM