[英]Is it inefficient to initialize a variable multiple times rather than reassigning one?
I'm building an app where I have to loop over an array of objects and for each one I'm calling a helper function.我正在构建一个应用程序,我必须在其中循环一组对象,并且对于每个对象我都调用一个助手 function。
In that helper function I need to pass a variable to another helper function.在那个助手 function 中,我需要将一个变量传递给另一个助手 function。
My question is, is it bad practice to initialize that variable in the first helper function every time?我的问题是,每次都在第一个助手 function 中初始化该变量是不好的做法吗?
Basically:基本上:
Example 1: Initialize b in funcA示例 1:在 funcA 中初始化 b
funcA(byte[] bytes) {
...
byte b = bytes[0];
funcB(b);
}
while(...) {
byte[] bytes;
funcA(bytes);
}
OR或者
Example 2: Initialize b outside and just reassign示例 2:在外部初始化 b 并重新分配
byte b;
funcA(byte[] bytes) {
...
b = bytes[0];
funcB(b);
}
while(...) {
byte[] bytes;
funcA(bytes);
}
Which is better?哪个更好? (I'm calling funcA approx 20-30 times) I suppose I could just do
funcB(bytes[0])
but I want to assign it to a variable for readability. (我调用 funcA 大约 20-30 次)我想我可以做
funcB(bytes[0])
但我想将它分配给一个变量以提高可读性。
It is bad practice not to initialize that variable in the helper function every time.每次都不要在帮助程序 function 中初始化该变量是不好的做法。
In general, variables should be defined in the narrowest scope possible.一般来说,变量应该定义在最窄的 scope 中。 It is more efficient to have variables defined only where they're used and not keep variables around when they're not used.
仅在使用变量的地方定义变量而不在不使用变量时保留变量会更有效。 "Creating the new variable here" is basically free;
“在这里创建新变量”基本上是免费的; it just becomes part of the memory allocated on the stack for this function.
它只是成为在堆栈上为此 function 分配的 memory 的一部分。
Performance concerns should almost never drive your system design.性能问题几乎不应该驱动您的系统设计。 First make sure that your code makes sense from logical point of view and implement it accordingly and then measure actual execution time, memory usage, etc.
首先确保您的代码从逻辑角度来看是有意义的并相应地实现它,然后测量实际执行时间、memory 使用情况等。
In your case that array should be defined and initialized where it's needed.在您的情况下,应该在需要的地方定义和初始化该数组。 I'm assuming you are passing some values in it, so it makes total sense to have it declared in
while
and passed further to funcA
.我假设您在其中传递了一些值,因此在
while
中声明它并进一步传递给funcA
是完全有意义的。 If you are going to pass empty uninitialized object to your function there is a great chance that you are doing something very wrong, and there is actually no need to pass that object at all.如果您要将空的未初始化 object 传递给您的 function ,那么您很可能做错了什么,实际上没有必要在所有地方传递 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.