简体   繁体   中英

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.

In that helper function I need to pass a variable to another helper function.

My question is, is it bad practice to initialize that variable in the first helper function every time?

Basically:

Example 1: Initialize b in funcA

funcA(byte[] bytes) {
    ...
    byte b = bytes[0];
    funcB(b);
}

while(...) {
    byte[] bytes;
    funcA(bytes);
}

OR

Example 2: Initialize b outside and just reassign

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.

It is bad practice not to initialize that variable in the helper function every time.

In general, variables should be defined in the narrowest scope possible. 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.

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.

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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