問題出處:http://stackoverflow.com/questions/9465193/gt0-vs-notfirst-vs-slice1
原發問者本來是想問 :gt(0) 及 :not(:first) 的差別,只是後來回答的人又拋出了個 .slice(1) 的方式,所以整個問題就變成在比較那個方式的處理速度較快囉。
在 :gt() Selector 頁面中有一段補充內容是這樣說的
Additional Notes:
Because :gt() is a jQuery extension and not part of the CSS specification, queries using :gt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(index) instead.
從以上內容可以知道 :gt(0) 及 :not(:first) 都是 jQuery 自訂的選擇器的功能,並不是標準的 CSS 選擇器,所以效能上就會差一點。若是考量到效能的話,官方也是建議使用 .slice(index) 來取代 :gt()。
筆者在 jsPref 建立一個效能測試頁,分別就是使用 :gt(0)、:not(:first)、.not(":first") 及 .slice(1) 等四種方式來取得元素,結果如下:
雖然每個瀏覽器的效能差異不一,但可以看到綠色那條線就是使用 .slice(1) 的效能,越長表示越快越好。
如果各位想在自己機器上測試的話,首先在 HTML 中放入 10 個 span:
1 2 3 4 5 6 7 8 9 10 11 12 | <body> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </body> |
然後寫個簡單的執行時間計算的程式,執行的動作分別就是使用 :gt(0)、:not(:first)、.not(":first") 及 .slice(1) 等四種方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | $(function(){ console.time(':gt(0)'); for(var i=0;i<10000;i++){ $('span:gt(0)'); } console.timeEnd(':gt(0)'); console.time(':not(:first)'); for(var i=0;i<10000;i++){ $('span:not(:first)'); } console.timeEnd(':not(:first)'); console.time('.not(":first")'); for(var i=0;i<10000;i++){ $('span').not(":first"); } console.timeEnd('.not(":first")'); console.time('.slice(1)'); for(var i=0;i<10000;i++){ $('span').slice(1); } console.timeEnd('.slice(1)'); }); |
這邊可以利用 Chrome 或是 Firefox 的外掛 Firebug 來做時間的計算,執行後輸出的結果如下:
從結果可以看到分別執行 10000 次後的時間統計,時間最短的一樣是 .slice(1) 的方式。
所以各位在使用 jQuery 時,若結果是一樣的話,盡量選擇效能較好的方式。