Which loop has better performance? Why?

后端 未结 8 1689
粉色の甜心
粉色の甜心 2020-11-27 11:24
String s = \"\";
for(i=0;i<....){
    s = some Assignment;
}

or

for(i=0;i<..){
    String s = some Assignment;
}
8条回答
  •  孤街浪徒
    2020-11-27 12:09

    It seems to me that we need more specification of the problem.

    The

    s = some Assignment;
    

    is not specified as to what kind of assignment this is. If the assignment is

    s = "" + i + "";
    

    then a new sting needs to be allocated.

    but if it is

    s = some Constant;
    

    s will merely point to the constants memory location, and thus the first version would be more memory efficient.

    Seems i little silly to worry about to much optimization of a for loop for an interpreted lang IMHO.

提交回复
热议问题