本文介绍了重复实例化变量/性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! //代码序列A for(int i = 0; i< 10; ++ i){ int k = something(); //更多代码使用k } //代码序列B int k ; for(int i = 0; i< 10; ++ i){ k = something(); // some更多代码使用k } 两个序列在​​性能方面完全相同,还是重复了 序列B中k的实例化与序列B中的单个实例相比有一定的成本吗? 如果k属于类类型怎么样? 谢谢,罗伯特 解决方案 谁能说?一个编译器可能与下一个编译器不同。如果你真的感兴趣的是然后编写程序并计时(或者查看 生成的机器代码)。就个人而言,我会惊讶地看到任何 的差异,但后来我从未真正研究过它。 至于班级版本,那么它取决于在课堂上(以及 编译器)。您正在将分配成本与复制成本进行比较 构造。哪个更有效率完全取决于课程是如何编写的,没有先验的理由期望更高效。 john 正如John提到的那样,第一个是一个结构,第二个是作业。 在某些情况下,有些课程会做同样的事情。其他人将在构造案例中进行更多的初始化。一些人可能会在 分配案例中做更多工作。 我更喜欢建筑案例,因为 限制范围造成的清晰度,除非我确定对象的构造比作业贵得多。 Niels Dybdahl 当然,一般来说,代码的清晰度是最重要的效率 保存所有。 john // Code sequence Afor (int i = 0; i < 10; ++i) {int k = something();// some more code which uses k}// Code sequence Bint k;for (int i = 0; i < 10; ++i) {k = something();// some more code which uses k}Are the two sequences exactly the same in terms of performance, or has therepeated instanciation of k in sequence A a certain cost compared with thesingle one instantiation in sequence B?What about if k were of a class type?Thanks, Robert 解决方案Who can say? One compiler could be different from the next. If you arereally interested then write the program and time it (or look at thegenerated machine code). Personally I would be surprised to see anydifference, but then I''ve never really looked into it.As for the class version then it depends upon the class (and on thecompiler). You are comparing the cost of assignment with the cost of copyconstruction. Which is more efficient depends entirely on how the class iswritten, There is no a priori reason to expect either to be more efficient.johnAs John mentions the first is a construction and the second an assignment.Some classes will do the same in those cases. Others will do some moreinitialization in the construction case. A few might do more work in theassignment case.I would prefer the construction case because of clarity caused by thelimited scope, unless I know for sure that the construction of the object ismuch more expensive than an assignment.Niels DybdahlAbsolutely, in general clarity of code is the most important efficiencysaving of all.john 这篇关于重复实例化变量/性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-22 19:39
查看更多