哪个是最佳的? [英] Which is optimal?

查看:101
本文介绍了哪个是最佳的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在循环中声明一个变量是好的,还是在Java中最佳声明。在循环内声明时是否还有任何性能成本?

Is declaring a variable inside a loop is good or declaring on the fly optimal in Java.Also is there any performance cost involved while declaring inside the loop?

例如。

List list = new ArrayList();
int value;

//populate list
for(int i = 0 ; i < list.size(); i++) {
  value = list.get(i);
  System.out.println("value is "+ value);
}



选项2:在循环内



Option 2: Inside the Loop

List list = new ArrayList();

//populate list
for(int i = 0; i < list.size(); i++) {
  int value = list.get(i);
  System.out.println("value is "+ value);
}


推荐答案

清洁代码,Robert C. Martin建议Java编码人员声明变量尽可能接近它们的使用位置。变量的范围不应超过必要的范围。将变量的声明接近其使用位置有助于为读者提供类型和初始化信息。不要过多关注性能,因为JVM非常擅长优化这些东西。而是专注于可读性。

In Clean Code, Robert C. Martin advises Java coders to declare variables as close as possible to where they are to be used. Variables should not have greater scope than necessary. Having the declaration of a variable close to where it's used helps give the reader type and initialization information. Don't concern yourself too much with performance because the JVM is pretty good at optimizing these things. Instead focus on readability.

BTW:如果您使用的是Java 5或更高版本,则可以使用以下new-for-Java-5显着修剪代码示例功能:

BTW: If you're using Java 5 or greater, you can significantly trim up your code example using the following new-for-Java-5 features:


  • foreach construct

  • generics

  • autoboxing

我重构了你的例子以使用上述新功能。

I've refactored your example to use the aforementioned new features.

List<Integer> list = new ArrayList<Integer>();

// populate list

for (int value : list) {
    System.out.println("value is " + value);
}

这篇关于哪个是最佳的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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