Difference between Initializing string with new and “ ”

前端 未结 8 1487
离开以前
离开以前 2021-01-27 08:21

Which one is correct and why:

String dynamic = new String();
dynamic = \" where id=\'\" + unitId + \"\'\";

Or

String dynamic = \" where id=\'\" + unitId + \"         


        
8条回答
  •  离开以前
    2021-01-27 09:06

    I would suggest you to do in this way

    String dynamic = " where id='" + unitId + "'";
    
    String dynamic  = new String();// DON'T DO THIS!
    dynamic = " where id='" + unitId + "'";
    

    The statement creates a new String instance each time it is executed, and none of those object creations is necessary. The argument to the String constructor (" where id='" + unitId + "'") is itself a String instance, functionally identical to all of the objects created by the constructor. If this usage occurs in a loop or in a frequently invoked method, millions of String instances can be created needlessly. The improved version is simply the following:

    String dynamic = " where id='" + unitId + "'";
    

提交回复
热议问题