What is the best way to add two strings together?

前端 未结 12 511
自闭症患者
自闭症患者 2020-12-01 23:35

I read somewehere (I thought on codinghorror) that it is bad practice to add strings together as if they are numbers, since like numbers, strings cannot be changed. Thus, ad

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 00:08

    I'm not a PHP guru, however, in many other languages (e.g. Python), the fastest way to build a long string out of many smaller strings is to append the strings you want to concatenate to a list, and then to join them using a built-in join method. For example:

    $result = array();
    array_push("Hello,");
    array_push("my");
    array_push("name");
    array_push("is");
    array_push("John");
    array_push("Doe.");
    $my_string = join(" ", $result);
    

    If you are building a huge string in a tight loop, the fastest way to do it is by appending to the array and then joining the array at the end.

    Note: This entire discussion hinges on the performance of an array_push. You need to be appending your strings to a list in order for this to be effective on very large strings. Because of my limited exposure to php, I'm not sure if such a structure is available or whether php's array is fast at appending new elements.

提交回复
热议问题