A newer version of this documentation is available.

View Latest

Function/Benchmark: fasterToLocalString

    January 5, 2025
    + 12

    Goal: Explore faster local time zone date formating.

    • This function fasterToLocalString demonstrates a faster alternative to the built-in JavaScript function toLocalString.

    • In Couchbase 6.6.0 the fasterToLocalString implementation is 708X faster than the v8 runner.

    • In Couchbase 7.0.0 the fasterToLocalString implementation is 177X faster than the upgraded v8 runner.

    • The above demonstrates that all date conversions should be benchmarked.

    • Requires Eventing Storage (or metadata collection) and a "source" collection.

    • Will operate on any mutation where doc.type === "basic_bkt_ops".

    • Deploy from now

    • Only mutate one document as this is a benchmark of ICU performance.

    javascript
    // To run configure the settings for this Function, docControlledSelfExpiry, as follows: // // Version 7.1+ // "Function Scope" // *.* (or try bulk.data if non-privileged) // Version 7.0+ // "Listen to Location" // bulk.data.source // "Eventing Storage" // rr100.eventing.metadata // Binding(s) - none // // Version 6.X // "Source Bucket" // source // "MetaData Bucket" // metadata // Binding(s) - none function fasterToLocalString(d) { // adjust the input date by the UTC offset var dadj = new Date(d.getTime() - d.getTimezoneOffset() * 60 * 1000); var hr = dadj.getUTCHours(); var min = dadj.getUTCMinutes(); var sec = dadj.getUTCSeconds(); var strLocalDate = (dadj.getUTCMonth()+1) + "/" + dadj.getUTCDate() + "/" + dadj.getUTCFullYear() + ", " + ((hr < 13) ? hr : (hr - 12)) + ":" + ((min<10) ? "0"+min : min) + ":" + ((sec<10) ? "0"+sec : sec) + ((hr < 12) ? " AM" : " PM"); // should be the same as d.toLocaleString('en-US') return strLocalDate; } function OnUpdate(doc, meta) { var cnt = 20000; var d = new Date(); var tbeg, tend; if (true) { // This crash a debug session refer to eventing-debugging-and-diagnosability.html // however it always work in no-debug but is very slow. tbeg = Date.now(); for (var i=1; i<=cnt; i++) { var res = d.toLocaleString('en-US'); if (i % cnt == 0) log("d.toLocaleString('en-US') ",res); } tend = Date.now(); log("d.toLocaleString('en-US') ", tend-tbeg + " ms."); } if (true) { tbeg = Date.now(); for (var i=1; i<=cnt; i++) { var res = fasterToLocalString(d); if (i % cnt == 0) log("fasterToLocalString(d) ",res); } tend = Date.now(); log("fasterToLocalString(d) ", tend-tbeg + " ms."); } }