JavaScript date processing functions, performance optimization Batch _ Basics

Source: Internet
Author: User
Tags dateformat

In fact, online writing JavaScript date format of a lot of blog, generally looked at, are not bad. The only regret is that the function has not been optimized for performance.
As the saying goes: Do not repeat the wheel. Google found a relatively good date format function, to start my optimization trip bar!
Google is looking for this date function function, it is estimated that everyone looks familiar, I used to be used. First look at the optimization and optimization before the efficiency of the comparison bar!
1, the optimization of the previous ToDate function (string conversion to date object), repeated execution 10,000 times, time consuming 660 milliseconds

2, optimize the DateFormat function (Date object format into a string), repeat 10,000 times, takes 676 milliseconds

3, after the optimization of the todate function, repeated execution 10,000 times, time consuming 122 milliseconds

4, after the optimized DateFormat function, repeats executes 10,000 times, takes 160 milliseconds

Why the difference is so big, in fact, I did not do much processing, just for batch processing do some caching, carefully observe all the online date format function, in fact, are used to match and replace. In fact, it is very performance-consuming, so I did a cache of regular matches and indexed the matching values. You don't have to do a regular match every time.

No Code no truth, next look at the truth!

(function (window) {var sinojh = {Version: "1.2", Copyright: "Copyright©sino-jh", Author: "Jeff L
  An ", Email:" jefflan@live.cn "}; 
    /** * Easy to add and override properties of the class * @param {Object} attributes added property */Function.prototype.prototypes = Function (attributes) {
    For (var A in attributes) {This.prototype[a] = Attributes[a];
  }
  }; /** * Get URL parameter * @param {string} parameter parameter name * @return {string} parameter value */sinojh.geturlparameter = function (PA
      Rameter) {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];
  }; /** * Date Formatted * @param {Date} Date Date Object * @param {string} formatstyle formatted style * @return {string} date-type 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+": Dat
    E.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]: ("+ 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 at time) {if (New RegExp ("+ K +")). Test (Formatstyle)) {Replacecache[k] = {
          REPLACE:REGEXP.$1}; Formatstyle = Formatstyle.replace (regexp.$1, regexp.$1.length = 1? Time[k]: ("+ time[k]"). Substring (("" + Time[k]). l
        Ength));
    } Sinojh.dateFormat.replaceCache = Replacecache;
  return formatstyle;
  };
  Sinojh.dateFormat.settings = {formatstyle: "Yyyy-mm-dd hh:mm:ss"}; /** * Convert date format string to date Object * @param {string} datestr date format string * @param {string} datestyle date format * @return {date} day The object of the period * 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].inde
        X, 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": "", "M": "00", "s": "
  "," S ":" 000 "});
  Sinojh.toDate.settings = {datestyle: "Yyyy-mm-dd hh:mm:ss"};
  Delete Function.prototype.prototypes;
WINDOW.JH = SINOJH;  } (this);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.