关于原语的快速问题
由于我的不好的例子,编辑了这个问题。这是我更新的问题:
以下速度和内存分配是否相等:
int b;
for (int i = 0; i < 1000; i++)
b = i;
和
for (int i = 0; i < 1000; i++)
int b = i;
Edited this question because of my bad examples.. Here is my updated question:
Would the following be equal in speed and memory allocation:
int b;
for (int i = 0; i < 1000; i++)
b = i;
and
for (int i = 0; i < 1000; i++)
int b = i;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
答案取决于您所说的“等于”的含义=)
The answer depends on what you mean by saying "equal" =)
不,不会的。
在第一种情况下,您为一个变量分配了 1000 个不同的值 - 并且您最终能够在构造函数完成后获得最后一个值 (999)。
在第二种情况下,您将调用本质上无操作的方法 1000 次。第二种方法没有副作用,也没有返回值,所以没什么用。局部变量仅在方法调用期间“存在”,而第一个示例中的实例变量是对象的一部分,因此将继续存在。
请注意,这并不限于基元 - 任何其他类型也会有相同的行为。
No, it wouldn't.
In the first case you've got one variable being assigned 1000 different values - and you end up being able to get hold of the last value (999) after the constructor has completed.
In the second case you're calling an essentially no-op method 1000 times. The second method has no side-effects and has no return value, so it's useless. The local variable only "exists" for the duration of the method call, whereas the instance variable in the first example is part of the object, so will live on.
Note that this isn't restricted to primitives - any other type would behave the same way too.
不。
Class1
中,变量a
是一个字段,可由类中的所有方法访问。Class2
中,情况并非如此:a
是方法assign
中的局部变量。assign
完成后,a
的值将被丢弃。No.
Class1
the variablea
is a field, accessible by all methods in the class.Class2
this is not the case:a
is a local variable within the methodassign
. Afterassign
finishes, the value ofa
is discarded.不,一个有一个实例变量
a
(Class1),一个没有。No, one has an instance variable
a
(Class1), and one has not.在第一个实例中,您已经将 b 声明为 int,并且每次循环执行时其值都会更新。在第二个例子中,每次循环执行时都会声明 b 并将其初始化为 i 的值。我不是 100% 确定,但我认为第二种情况需要更多的内存,但我认为速度差异不会很明显。
In the first instance you've already declared b as an int and its value is updated each time the loop executes. In the second, b is declared and initialized to the value of i each time the loop executes. I'm not 100% sure but I think that the second case is more memory intensive but I don't think that the speed difference would be noticeable.
值得注意的是,任何有价值的编译器,并且我坚信 JIT 值得大量盐,只会在第二种情况下为“b”ONCE 留出空间,即“声明”阶段将毫无意义。
It's worth noting that any compiler worth its salt, and I firmly believe the JIT to be worth lots of salt, would just set aside space for "b" ONCE in the second case, i.e. the 'declaration' phase would be meaningless.
你尝试过这个吗?它甚至无法编译!
来自编译器的错误消息:
循环体必须至少包含一条语句。变量声明不是语句,因此只有变量声明的循环是无效的。
Have you tried this out? It doesn't even compile!
Error messages from the compiler:
The body of a loop must contain at least one statement. A variable declaration is not a statement, so a loop with just a variable declaration is invalid.