英文:
Object with static methods vs object methods -> which is more effecient?
问题
在Lucee / Coldfusion中,如果我有一个对象,在init()中什么都不做,也没有属性,只有一些辅助函数,以下两者哪个在性能/内存方面更高效,为什么呢?
// 公共对象方法
var rsData = new foo.bar.Object().getList();
对比
// 公共静态方法
var rsData = foo.bar.Object::getList();
我一直在思考这个问题,但不确定答案。
英文:
In Lucee / Coldfusion, if I have an object that doesn't do anything in an init() nor has properties, and all that it has are helper functions, which of the following two would be more efficient performance / memory wise, and why please?
// public object based function
var rsData = new foo.bar.Object().getList();
vs
// public static function
var rsData = foo.bar.Object::getList();
I've been debating this and am not sure of the answer.
答案1
得分: 2
这是一个"先入为主"的情况。
性能在这里不应该考虑,因为差异将是微不足道的。如果你甚至还没有编写第一个版本的代码,并且还没有性能受限制的情况要解决:这是一种过早优化的情况。
如果CFC是一个库而不是对象的表示:使用类(静态)方法。如果它是对象的表示:使用对象方法。这是你应该进行推理的方式。不是某种(在这一点上完全是感知的)性能考虑。
请记住,出于测试目的,内联方法调用 - 更适合静态方法 - 不可能绕过(例如:通过模拟/存根/双倍),因此应该谨慎使用静态方法的用法。如果纯粹是算法性能良好且没有副作用,那么这不是问题。通常情况下,这并不是情况,因为规划不周或有机代码的演变。还要记住,静态引用(MyClass::myStaticMethod
)是一个硬编码的依赖关系,并且本质上增加了它所在代码的复杂性。
在使用静态方法调用之前,应该考虑这些考虑因素。不是性能。
从本质上讲,静态方法调用需要加载类一次,而对象方法具有对象创建的开销。不过这种情况无需多言。
英文:
This is a "begging the question" situation.
Performance ought not be a consideration here, as the difference will be negligible. If you haven't even written the first iteration of the code yet, and don't yet have a performance-bound situation to address: this is a case of premature optimisation.
If the CFC is a library rather than the representation of an object: use class (static) methods. If it's a representation of an object: use object methods. That's what you ought to be reasoning. Not some (entirely perceived, at this point) performance consideration.
Bear in mind that for testing purposes, inline method calls - which static methods lend themselves more to - are not possible to bypass (eg: via mocking / stubbing / doubling), so one ought to be... circumspect... about the static method's usage. If it's purely algorithmic so performant and has no side effects, then this is not an issue. This is often not the case as poorly planned/organic code evolves. Also bear in mind that a static reference (MyClass::myStaticMethod
) is a hard-coded dependency, and innately increases the complexity of the code it is within.
These are the sorts of considerations one ought to be making before using static method calls. Not performance.
Intrinsically, that said, static method invocation requires the class to be loaded once for the lifetime of the app, whereas an object method has overhead of the object being created. That kinda goes without saying though.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论