2018年12月14日 星期五

[JavaScript] 索引類別是否影響速度

一個物件的索引可以是數字也可以是字串。是否影響速度?
LeetCode一道題目「Longest String Without Repeating Characters」中,我使用了以下方法解題:
===
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    let head = -1;
    let max = 0;
    let last = {};
    for (let i = 0, len = s.length; i < len; i++) {
        let c = <INDEX>; // INDEX
        if (!(c in last)) {
            last[c] = -1;
        } else {
            head = Math.max(head, last[c]);
        }
        max = Math.max(max, i - head);
        last[c] = i;
    }
    return max;
};
===.
在<INDEX>那邊我有了兩個版本:一個是直接拿s[i]當索引的字元版本;另一個是用s.charCodeAt(i)取得ASCII碼,以數值作為索引的數值版本。
字元版本跑了160ms,數值版只要76~80ms,有著十分明顯的差距。
因此,若求速度的話,還是要用數值索引會比較適當。

[HTML] ribody

怕自己忘記,稍微紀錄一下。 各種各種理由(其中一個就是Vue,不能綁定在body上),導致時常需要一個包在body中的div,當作body來用,像這樣: === <body>     <div id="divBody">   ...