js中高效拼接字符串


寫在前面

面試的過程,很有可能面試到c#那種方式拼接字符串更高效,然后就會引申到js中的拼接方式。這也是我在面試中遇到的問題,當時,也真沒比較過js中到底哪種方式更高效。然后,跟猜測一樣,說了使用數組的方式,然后使用join方法實現。

代碼測試

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5     <title>字符串拼接</title>
 6     <script type="text/javascript">
 7         var start = new Date();
 8         var str = "";
 9         for (var i = 0; i < 1000000; i++) {
10             str += "test";
11         }
12         var end = new Date();
13         document.writeln("+拼接字符串,耗時:" + (end.getMilliseconds() - start.getMilliseconds()));
14         document.writeln("<br/>");
15         var begin = new Date();
16         var arry = new Array();
17         for (var i = 0; i < 1000000; i++) {
18             arry.push("test");
19         }
20         arry.join("");
21         var stop = new Date();
22         document.writeln("數組方式拼接字符串,耗時:" + (stop.getMilliseconds() - begin.getMilliseconds()));
23     </script>
24 </head>
25 <body>
26 </body>
27 </html>

測試結果
IE11

+拼接字符串,耗時:39
數組方式拼接字符串,耗時:31

IE11兼容性視圖

+拼接字符串,耗時:40
數組方式拼接字符串,耗時:33

IE10

+拼接字符串,耗時:39
數組方式拼接字符串,耗時:32

IE9

+拼接字符串,耗時:36
數組方式拼接字符串,耗時:33

IE8

+拼接字符串,耗時:35
數組方式拼接字符串,耗時:35

IE7

+拼接字符串,耗時:37
數組方式拼接字符串,耗時:35

總結

在面試過程中遇到的一個知識點,在此記錄一下。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM