javascript日期處理函數,對批處理做了性能優化

openkk 12年前發布 | 28K 次閱讀 JavaScript開發 JavaScript

      俗話說:不要重復造輪子。google上找了一個比較不錯的日期格式化函數,來開始我的優化之旅吧!

 

      google上找的這個日期函數化函數,估計大家都很眼熟,以前我也一直在用。先看看優化后和優化前的效率對比吧!

 

1、優化之前的toDate函數(字符串轉換成Date對象),重復執行1萬次,耗時660毫秒

javascript日期處理函數,對批處理做了性能優化

 

 

2、優化之前的dateFormat函數(Date對象格式化成字符串),重復執行1萬次,耗時676毫秒

javascript日期處理函數,對批處理做了性能優化

 

 

3、優化過后的toDate函數,重復執行1萬次,耗時122毫秒

javascript日期處理函數,對批處理做了性能優化

 

 

4、優化后的dateFormat函數,重復執行1萬次,耗時160毫秒

javascript日期處理函數,對批處理做了性能優化

 

 

 

       為什么前后差別這么大,其實我也沒做多少處理,只是為批處理做了一些緩存而已,認真觀察所有網上那些日期格式函數,其實都是用正則進行匹配和替換。其實正則是很耗性能的,于是我在正則匹配的地方做了緩存,把匹配值建立索引。以后就不用每次都去做正則匹配了。

 

      無代碼無真相,接下來看看真相吧!

(function(window) {
    var sinojh = {
        Version : "1.2",
        Copyright : "Copyright© sino-jh 2012",
        Author : "Jeff Lan",
        Email : "jefflan@live.cn"
    };
    /**
     * 方便于添加和重寫類的屬性
     * @param {Object} attributes 添加的屬性
     */
    Function.prototype.prototypes = function(attributes) {
        for ( var a in attributes) {
            this.prototype[a] = attributes[a];
        }
    };
    /**
     * 獲取Url參數
     * @param {String} parameter 參數名
     * @return {String} 參數值
     */
    sinojh.getUrlParameter = function(parameter) {
        if (!sinojh.getUrlParameter.cache) {
            var url = window.location.href;
            var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
            var cache = {};
            for ( var i in paraString) {
                var j = paraString[i];
                cache[j.substring(0, j.indexOf("="))] = j.substring(j.indexOf("=") + 1, j.length);
            }
            sinojh.getUrlParameter.cache = cache;
        }
        return sinojh.getUrlParameter.cache[parameter];
    };
    /**
     * 日期格式化
     * @param {Date} date 日期對象
     * @param {String} formatStyle 格式化樣式
     * @return {String} 日期型字符串
     */
    sinojh.dateFormat = function(date, formatStyle) {
        formatStyle = formatStyle ? formatStyle : sinojh.dateFormat.settings.formatStyle;
        var time = {
            "M+" : date.getMonth() + 1,
            "d+" : date.getDate(),
            "h+" : date.getHours(),
            "m+" : date.getMinutes(),
            "s+" : date.getSeconds(),
            "S" : date.getMilliseconds()
        };
        if (formatStyle == sinojh.dateFormat.formatStyleCache) {
            var replaceCache = sinojh.dateFormat.replaceCache;
            if (replaceCache["y+"]) {
                formatStyle = formatStyle.replace(replaceCache["y+"].replace, (date.getFullYear() + "").substring(replaceCache["y+"].index));
            }
            for ( var k in time) {
                if (replaceCache[k]) {
                    formatStyle = formatStyle.replace(replaceCache[k].replace, replaceCache[k].replace.length == 1 ? time[k] : ("00" + time[k]).substring(("" + time[k]).length));
                }
            }
        } else {
            sinojh.dateFormat.formatStyleCache = formatStyle;
            var replaceCache = {};
            if (new RegExp("(y+)").test(formatStyle)) {
                var index = 4 - RegExp.$1.length;
                replaceCache["y+"] = {
                    replace : RegExp.$1,
                    index : index
                };
                formatStyle = formatStyle.replace(RegExp.$1, (date.getFullYear() + "").substring(index));
            }
            for ( var k in time) {
                if (new RegExp("(" + k + ")").test(formatStyle)) {
                    replaceCache[k] = {
                        replace : RegExp.$1
                    };
                    formatStyle = formatStyle.replace(RegExp.$1, RegExp.$1.length == 1 ? time[k] : ("00" + time[k]).substring(("" + time[k]).length));
                }
            }
            sinojh.dateFormat.replaceCache = replaceCache;
        }
        return formatStyle;
    };
    sinojh.dateFormat.settings = {
        formatStyle : "yyyy-MM-dd hh:mm:ss"
    };
    /**
     * 將日期格式的字符串轉換成Date對象
     * @param {String} dateStr 日期格式字符串
     * @param {String} dateStyle 日期格式
     * @return {Date} 日期對象
     */
    sinojh.toDate = function(dateStr, dateStyle) {
        dateStyle = dateStyle ? dateStyle : sinojh.toDate.settings.dateStyle;
        var compare = sinojh.toDate.compare;
        var result = new sinojh.toDate.result();
        if (dateStyle == sinojh.toDate.settings.dateStyleCache) {
            var indexCache = sinojh.toDate.indexCache;
            for ( var k in compare) {
                if (indexCache[k]) {
                    result[compare[k]] = dateStr.substring(indexCache[k].index, indexCache[k].index + indexCache[k].length);
                }
            }
        } else {
            var indexCache = {};
            for ( var k in compare) {
                if (new RegExp("(" + k + ")").test(dateStyle)) {
                    var index = dateStyle.indexOf(RegExp.$1);
                    var length = RegExp.$1.length;
                    indexCache[k] = {
                        index : index,
                        length : length
                    };
                    result[compare[k]] = dateStr.substring(index, index + length);
                }
            }
            sinojh.toDate.indexCache = indexCache;
            sinojh.toDate.settings.dateStyleCache = dateStyle;
        }
        return new Date(result["y"], result["M"] - 1, result["d"], result["h"], result["m"], result["s"], result["S"]);
    };
    sinojh.toDate.compare = {
        "y+" : "y",
        "M+" : "M",
        "d+" : "d",
        "h+" : "h",
        "m+" : "m",
        "s+" : "s",
        "S" : "S"
    };
    sinojh.toDate.result = function() {
    };
    sinojh.toDate.result.prototypes( {
        "y" : "",
        "M" : "",
        "d" : "",
        "h" : "00",
        "m" : "00",
        "s" : "00",
        "S" : "000"
    });
    sinojh.toDate.settings = {
        dateStyle : "yyyy-MM-dd hh:mm:ss"
    };
    delete Function.prototype.prototypes;
    window.jh = sinojh;
}(this); 
此文原創,轉載請注明原文出處 http://jefflan.iteye.com/blog/1333578 ,多謝!

 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!