Declare an object inside or outside a loop?

前端 未结 16 837
广开言路
广开言路 2020-12-07 17:15

Is there any performance penalty for the following code snippet?

for (int i=0; i         


        
16条回答
  •  醉酒成梦
    2020-12-07 18:14

    I've actually in front of me a code which looks like this:

    for (int i = offset; i < offset + length; i++) {
        char append = (char) (data[i] & 0xFF);
        buffer.append(append);
    }
    ...
    for (int i = offset; i < offset + length; i++) {
        char append = (char) (data[i] & 0xFF);
        buffer.append(append);
    }
    ...
    for (int i = offset; i < offset + length; i++) {
        char append = (char) (data[i] & 0xFF);
        buffer.append(append);
    }
    

    So, relying on compiler abilities, I can assume there would be only one stack allocation for i and one for append. Then everything would be fine except the duplicated code.

    As a side note, java applications are known to be slow. I never tried to do profiling in java but I guess the performance hit comes mostly from memory allocation management.

提交回复
热议问题