[英]Should a utlity class be instantiated?
I am currently working on a new project for university and was curious as to the best way to handle a class I've created to perform utility operations such as hashing passwords. 我目前正在为一个大学的新项目工作,并且对处理我创建的类以执行诸如哈希密码之类的实用程序操作的最佳方式感到好奇。
Should the utility class contain static methods so that I call them like 实用程序类是否应包含静态方法,以便我将其命名为
Utilities.hashPassword(password,salt);
Or should I create a new instance for each call 还是应该为每个调用创建一个新实例
new Utilities().hashPassword(password, salt);
Right now I have a new instance for each call to a function inside that class, but im concerned about the performance implications of this and am wondering if its even nessecary to do. 现在,对于该类中的函数的每个调用,我都有一个新实例,但是我担心此函数的性能影响,并且想知道其是否必要。
My original reason for instantiating them was because I wasn't sure how thread-safety worked and was concerned that multiple users calling the same static function would cause problems. 我实例化它们的最初原因是因为我不确定线程安全性如何工作,并且担心多个用户调用相同的静态函数会导致问题。 After reading some material on java concurrency I'm now pretty sure that even if the method is static it would be thread-safe.
在阅读了有关Java并发性的一些资料之后,我现在非常确定,即使该方法是静态的,它也是线程安全的。
Should I change them all to static methods? 我应该将它们全部更改为静态方法吗? Would this improve performance?
这样会提高性能吗? Right now my test server buckles under load.
现在,我的测试服务器在负载下弯曲。
Thanks 谢谢
Thread-safety does not care if a method is static or a true member method. 线程安全并不关心方法是静态的还是真正的成员方法。 Thread-safety cares about concurrent modification to data.
线程安全性关注数据的并发修改。 So, if your method is updating some generic data structure, you are NOT thread-safe just by making it static.
因此,如果您的方法正在更新某些通用数据结构,则仅使其静态化就不是线程安全的。
Arguments against "static": anything that is static is very hard to mock within unit tests. 反对“静态”的论点:任何静态的东西都很难在单元测试中模拟。 So be really careful about making stuff static just for convenience.
因此,为方便起见,请务必小心使内容静态化。
Regarding the performance aspect: object creation is very cheap in java (not completely free, but cheap). 关于性能方面:在Java中对象创建非常便宜(不是完全免费,但很便宜)。 In your case - you could keep it a member method - just avoid to throw away your utility object all the time.
对于您的情况-您可以将其保留为成员方法-避免避免始终丢掉实用程序对象。
Should I change them all to static methods?
我应该将它们全部更改为静态方法吗?
Yes. 是。 Utility method should be static.
实用程序方法应该是静态的。 Because, instead of
new Utilities().hashPassword(password, salt);
因为,而不是
new Utilities().hashPassword(password, salt);
use only static import of hashPassword(password, salt)
. 仅使用静态导入的
hashPassword(password, salt)
。 Shorter and easier to read. 更短,更容易阅读。
Would this improve performance?
这样会提高性能吗?
Yes. 是。 Declaring static will save memory.
声明为static将节省内存。 It will also improve readability.
它还将提高可读性。
See also: Java: when to use static methods 另请参见: Java:何时使用静态方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.