在类中存储全局常量的性能
我最近开始在项目中使用类,用途之一是在 private
数组中设置和存储全局常量。我想知道这是否是常见的做法,如果我在类中对 fetch 函数进行大量调用(例如,每当我需要站点名称、电子邮件地址或 MySQL 详细信息时,这会很糟糕,而且最重要的是,速度很慢) )。
我不会发布代码,因为它非常基本;只是一个返回
带有给定键的数组中项目值的函数。
I've recently started using classes in my projects, and one of the uses is to set and store global constants in a private
array. I'm wondering if this is common practice, bad and, most importantly, slow if I'm doing lots of calls to the fetch function in the class (lots as in, whenever I need the site name, an email address or MySQL details).
I'm not posting the code because it's really basic; just a function that returns
the value of an item in the array with the key given.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不用担心这个。
沿着这条路,您将了解单例模式和注册表模式。不要使用这些模式,它们是反模式。
尝试按照SOLID原则构建设计,你的对象的耦合将会越来越少。站点名称将存储在类中,该类将向页面输出内容,其他类不需要此常量。电子邮件地址将仅存储在 Mailer 类(或其配置文件中)中,其他类不需要此常量。等等。
类,包含所有常量和所有配置,它是一种“God object”,它是一个也是反模式(不好的做法)。
不用担心 getter 和 setter 的性能。
Don't worry about that.
Going this way, you will come to patterns Singleton and Registry. Don't use these patterns, it's anti-patterns.
Try to build design by the SOLID principles, and your objects will be coupled less and less. The Site Name will be stored in the class, which will output content to the page, and other classes will not need this constant. The Email Address will be stored only in the Mailer class (or in his configuration file), and other classes will not need this constant. And so on.
Class, which contain all constants and all configurations it's kind of a 'God object', and it's an anti-pattern (bad practice) too.
Don't worry about performance of getters and setters.
除非您在该数组中声明数百个元素,否则应该没问题,这看起来很容易获取和设置:)
我在这里注意到的是,为什么不将所有信息存储在私有数组中,而不是将所有信息存储在私有数组中声明实例变量?例如,而不是
这样做应该是一个更好的做法
,其背后的原因是,当你需要获取网站的单个信息时,你不需要获取整个数组,只需获取一个它的元素,看起来不太好。使用实例变量更方便获取和设置。
使用下面的代码是不是看起来更好、更方便?
It should be fine unless you declare hundreds of elements in that array, which will look note very nice to get and set :)
What I notice here is that, instead of storing all the information in a private array, why don't you just declare the instance variables? For example, instead of
It should be a better practice to do like this
The reason behind this is that, when you need to get a single piece of information of your website, you don't need to get the whole array and just get a element of it, which look not very nice. Using instance variables is just more convenient to get and set.
Does it look nicer and more handy with this code below?