简体   繁体   English

如何在极简主义条件声明中获得更好的表现?

[英]How to get better performance in a minimalist conditional statement?

I work with JavaScript but I always wonder this for all the languages. 我使用JavaScript,但我总是想知道所有语言。

Do I get better performance doing this: 这样做能否获得更好的表现:

var i = 0;
if(j < 0) 
{
   i = 1;
}

Or this? 或这个?

var i;
if(j < 0) 
{
    i = 1;
}
else 
{
    i = 0;
}

With 50% chance to have j < 0 有50%的几率让j < 0

That will depend on the implementation of javascript engine, which, at least if you write your code for the Web, is out of your control. 这将取决于javascript引擎的实现,至少如果你为Web编写代码,它就是你无法控制的。

One browser might be faster with first version of the code, the other with the second version. 对于第一版本的代码,一个浏览器可能更快,另一个浏览器可能更快。 And tomorrow it might change. 明天它可能会改变。

Do not optimize things like this unless you have pinned down this one line of code as a bottleneck of your task. 除非你将这一行代码固定为任务的瓶颈,否则不要优化这样的事情。

You might want to read when to optimize . 您可能想要了解何时进行优化

You will be better of to write readable and well designed code, and let the browser vendors wory about machine level optimisations. 您将更好地编写可读且设计良好的代码,并让浏览器供应商了解机器级优化。

The things you should optimize are algorithms, and not language specific constructions. 您应该优化的是算法,而不是语言特定的构造。

Neither of your code makes much of a difference. 你的代码都没有太大区别。 Depends on the JS engine of course but todays engines are pretty advanced and optimize code very well(especially V8 on chrome and node.js). 当然取决于JS引擎,但今天的引擎非常先进并且非常好地优化了代码(尤其是chrome和node.js上的V8)。

Benchmark it. 基准吧。 You can use simple console.time('label'); console.timeEnd('label') 你可以使用简单的console.time('label'); console.timeEnd('label') console.time('label'); console.timeEnd('label') at least in Chrome. console.time('label'); console.timeEnd('label')至少在Chrome中。

In my opinion your code looks ugly and like a bloat. 在我看来,你的代码看起来很丑陋,就像一个臃肿。 A lot of space is consumed with no content. 消耗大量空间而没有内容。 I would prefer this approach as it reads much faster and you should care about readability as much as performance : 我更喜欢这种方法,因为它读取速度更快,你应该关注可读性性能

var i;    
if(j < 0) {
    i = 1;
} else {
    i = 0;
}

Also you have an access to ternary operator: 您还可以访问三元运算符:

var i = j < 0 ? 1 : 0;

which is readable if you do not nest it. 如果你不嵌套它是可读的。 Again - performance wise all of them are equal and will differt by maybe a millisecond or two so you should not care about performance in such simple cases. 再次 - 性能明智,所有这些都是相同的,并且可能会有一两毫秒的差异,所以你不应该在这么简单的情况下关心性能。 Care about readability :) 关心可读性:)

Also performance will depend on your j value. 性能也取决于你的j值。 If optimizer will see that you set j to 1 . 如果优化器将看到您将j to 1设置j to 1 It will short-circuit the whole code and simply set i = 0 . 它会使整个代码短路并简单地设置i = 0 IMHO in such simple cases it's not useful to spend time to search for improvement except for readability :). 恕我直言,在这种简单的情况下,除了可读性之外,花时间寻找改进是没有用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM