可读性与性能 [英] Readability vs Performance

查看:113
本文介绍了可读性与性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我们在工作中讨论了局部变量对Java代码的性能与可读性的影响。我的一些同事认为这样的声明

Recently we had a discussion at work about the impact of local variables on the performance vs readability of Java code. Some of my colleagues are of the oppinion that declarations like this

new DoSomethingCmd(new SelectionContext(context, keys), infoStuff.getCurrentRole().getRole_id()).execute(getResultContainer());

将大大提高应用程序的性能。他们愿意为此牺牲代码的可读性。他们主张这个权利对吗?

will give the application a considerable performance boost. They are willing to sacrifice code readability for this. Are they right in claiming this? Is the above version significantly more performant than, say, this one?

final SelectionContext selectionContext = new SelectionContext(context, keys);
final String roleId = infoStuff.getCurrentRole().getRole_id();
final DeleteSomethingCmd deleteSomethingCmd = new DeleteSomethingCmd(selectionContext,roleId);
deleteSomethingCmd.execute(getResultContainer());

我意识到第一条陈述本身并没有那么难理解,但是

I realise that the first statement isn't all that difficult to grasp in and on itself, but the complexity adds up rather quickly when most of your code is structured like that.

感谢您的输入。

推荐答案

优化版本的唯一优点是,堆栈中的变量较少,从而稍微增加了内存消耗。应该仔细评估绩效(Google如何衡量一个问题的基准),但是我严重怀疑它是否会产生明显的影响。

The only thing that the "optimized" version makes is that you have a few variables less in the stack, slightly increasing your memory consumption. Performance should be measured carefully (google how to benchmark an issue), but I seriously doubt that it has any noticeable effect.

经常不使用的代码只会浪费开发人员的时间,这是很昂贵的。

Also, spending time improving performance in a piece of code that is not used often is just a waste of developer time, which is expensive.

在这种情况下,可读性应该是赢家。

In this case, readability should win the day.

编辑:无论如何,如果您使用适当的缩进,我不认为这两个版本在可读性方面都不太相同:

Anyway, if you use proper indentation, I do not thingk the two versions are too different in readability terms:

new DoSomethingCmd(
    new SelectionContext(context, keys),
    infoStuff.getCurrentRole().getRole_id()
    ).execute(getResultContainer());

此文本的优点是您没有定义变量( selectionContext roleId )(因此,当您再次阅读该方法时,它们不会与更多持久变量混合使用)。无论如何,这是可以解释的;最重要的是,除非有动机,否则您不必担心优化。

The advantage of this text is that you do not have defined variables (selectionContext, roleId)that are no longer needed (so when you read the method again they do not mix with more "persistent" variables). Anyway, that is open to interpretation; the bottom line is that you should not worry with optimization unless you have a motive to do so.

除此之外,还有一些Java编程准则可以使您真正地确实有用的实用技巧(例如,使用 StringBuilder 连接字符串)。

Apart from that, there are some guidelines to Java programming that give you really useful tricks that really help you (v.g. using StringBuilder to concatenate strings).

这篇关于可读性与性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆