热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

关于循环有效工作的两个问题-Twoquestionsaboutefficientworkwithloops

1.Supposefollowingsituations.First:intx;for(inti0;i<MAX;i++){somemagic

1. Suppose following situations.

First:

int x;
for (int i = 0; i 

Second:

for (int i = 0; i 

So which piece of code is better and more efficient?

那么哪一段代码更好,更有效?

2. Another two situations.

First:

int size = array.length;
for (int i = 0; i 

Second:

for (int i = 0; i 

Is it more efficient to save array length to variable?

将数组长度保存到变量是否更有效?

2 个解决方案

#1


1  

1. What you should be more concerned with here, is not efficiency, but scope. Generally, you should strive to keep your variables as locally scoped as possible. This means, if you only need x within the loop, you should define it within the loop.

你在这里应该更关心的不是效率,而是范围。通常,您应该尽可能地将变量保持为本地范围。这意味着,如果在循环中只需要x,则应在循环内定义它。

You get a number of benefits with keeping your variables as locally scoped as possible:

将变量保持为本地作用域可以获得许多好处:

  • Your code will be much more readable to someone else
  • 您的代码对其他人来说更具可读性

  • You won't accidentally assign to, or use the value of a variable you defined further up in your code that is still in scope, thus minimizing errors in your program
  • 您不会意外地分配或使用您仍在范围内的代码中进一步定义的变量的值,从而最大限度地减少程序中的错误

  • Most importantly, the garbage collector will free up any memory used by the variable as soon as it goes out of scope, keeping your program's performance high, and memory usage low.
  • 最重要的是,垃圾收集器一旦超出范围就会释放变量使用的所有内存,从而保持程序性能高,内存使用率低。

You can read up more on variable scope and best practices from Josh Bloch's excellent book, "Effective Java" (scope is discussed in items 13 and 45). You might also want to read item 55, which discusses why it is important to optimize judiciously.

您可以从Josh Bloch的优秀书籍“Effective Java”(范围在第13和45项中讨论)中阅读有关可变范围和最佳实践的更多信息。您可能还想阅读第55项,其中讨论了明智地优化的重要性。

2. For the second part of your question, see The Skeet's answer here.

2.关于问题的第二部分,请参阅Skeet的答案。

Here's an example:

这是一个例子:

public static void main(String[] args) {
    for(int i=0; i

This outputs:

size: 2
i: 0
size: 4
i: 1
size: 4
i: 2
size: 8
i: 3
size: 0

Notice how getSize() is called for every iteration of the loop. In your example, calling .length won't make a huge difference, as the JIT runtime will know how to optimize this call. But imagine getSize() was a more complex operation, like counting the number of rows in a database table. Your code will be super slow as every iteration of the loop will call getSize(), resulting in a database roundtrip.

注意如何为循环的每次迭代调用getSize()。在您的示例中,调用.length不会产生巨大的差异,因为JIT运行时将知道如何优化此调用。但是想象一下getSize()是一个更复杂的操作,比如计算数据库表中的行数。您的代码将非常慢,因为循环的每次迭代都将调用getSize(),从而导致数据库往返。

This is when you would be better off evaluating the value before hand. You can do this and still retain minimal scope for size, like this:

这是你最好先评估价值的时候。您可以执行此操作并仍保留最小的大小范围,如下所示:

public static void main(String[] args) {
    for(int size = getSize(), i=0; i

Notice how getSize() is only called once, and also, the size variable is only available inside the loop and goes out of scope as soon as the loop completes.

注意getSize()只被调用一次,而且size变量只在循环内部可用,并且在循环完成后就会超出范围。

#2


2  

length is just a property in the array object, it doesn't take any time in getting the length.

length只是数组对象中的一个属性,它不需要任何时间来获取长度。

It is the same as reading from a variable it doesn't need to loop over the whole array to get the length.

它与从变量读取相同,它不需要遍历整个数组来获得长度。

And the first two are just scopes.

前两个只是范围。

Local - only available within the loop.

本地 - 仅在循环内可用。

Global - available throught.

全球 - 可通过。


Assume you want remainders of numbers when divided by 2.

假设你想要除以2的剩余数字。

for(int i = 0; i <10; ++i)
{
 int remainder = i % 2;
 System.out.println(remainder);
}

And assume calculating the sum of first 10 natural numbers.

并假设计算前10个自然数的总和。

int sum = 0;
for(int i = 0; i <= 10; ++i)
 {
    //declaring sum here doesnt make sense
     sum += i;
 } 
System.out.println(sum);//sum is available here.

PS: you could just the sum of n natural numbers formula.

PS:你可以只用n个自然数公式的总和。


推荐阅读
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了一个在线急等问题解决方法,即如何统计数据库中某个字段下的所有数据,并将结果显示在文本框里。作者提到了自己是一个菜鸟,希望能够得到帮助。作者使用的是ACCESS数据库,并且给出了一个例子,希望得到的结果是560。作者还提到自己已经尝试了使用"select sum(字段2) from 表名"的语句,得到的结果是650,但不知道如何得到560。希望能够得到解决方案。 ... [详细]
  • This article discusses the efficiency of using char str[] and char *str and whether there is any reason to prefer one over the other. It explains the difference between the two and provides an example to illustrate their usage. ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • 猜字母游戏
    猜字母游戏猜字母游戏——设计数据结构猜字母游戏——设计程序结构猜字母游戏——实现字母生成方法猜字母游戏——实现字母检测方法猜字母游戏——实现主方法1猜字母游戏——设计数据结构1.1 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • 前景:当UI一个查询条件为多项选择,或录入多个条件的时候,比如查询所有名称里面包含以下动态条件,需要模糊查询里面每一项时比如是这样一个数组条件:newstring[]{兴业银行, ... [详细]
  • Android自定义控件绘图篇之Paint函数大汇总
    本文介绍了Android自定义控件绘图篇中的Paint函数大汇总,包括重置画笔、设置颜色、设置透明度、设置样式、设置宽度、设置抗锯齿等功能。通过学习这些函数,可以更好地掌握Paint的用法。 ... [详细]
  • 如何用UE4制作2D游戏文档——计算篇
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了如何用UE4制作2D游戏文档——计算篇相关的知识,希望对你有一定的参考价值。 ... [详细]
  • 判断数组是否全为0_连续子数组的最大和的解题思路及代码方法一_动态规划
    本文介绍了判断数组是否全为0以及求解连续子数组的最大和的解题思路及代码方法一,即动态规划。通过动态规划的方法,可以找出连续子数组的最大和,具体思路是尽量选择正数的部分,遇到负数则不选择进去,遇到正数则保留并继续考察。本文给出了状态定义和状态转移方程,并提供了具体的代码实现。 ... [详细]
  • IjustinheritedsomewebpageswhichusesMooTools.IneverusedMooTools.NowIneedtoaddsomef ... [详细]
  • Oracle优化新常态的五大禁止及其性能隐患
    本文介绍了Oracle优化新常态中的五大禁止措施,包括禁止外键、禁止视图、禁止触发器、禁止存储过程和禁止JOB,并分析了这些禁止措施可能带来的性能隐患。文章还讨论了这些禁止措施在C/S架构和B/S架构中的不同应用情况,并提出了解决方案。 ... [详细]
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
author-avatar
PHP猎人
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有