openhab / openhab-js

openHAB JavaScript Library for JavaScript Scripting Automation
https://www.openhab.org/addons/automation/jsscripting/
Eclipse Public License 2.0
38 stars 31 forks source link

[utils] Add Java to JS conversion for `Instant` & `ZonedDateTime` #267

Closed florian-h05 closed 1 year ago

florian-h05 commented 1 year ago

Adds two new methods to the utils namespce and makes use of them internally:

florian-h05 commented 1 year ago

FYI, I have benchmarked the performance of these implementations against toString and parsing that string:

var Instant = Java.type('java.time.Instant');
var ins = Instant.now();

console.log('Benchmarking Instant.parse conversion ...')
var start = time.Instant.now().toEpochMilli();

for (var i = 0; i < 50; i++) {
  time.Instant.parse(ins.toString())
}

var end = time.Instant.now().toEpochMilli();
console.log('Benchmark finshed, took ' + (end - start) + ' ms')

console.log('Benchmarking advanced Instant conversion ...')
var start = time.Instant.now().toEpochMilli();

for (var i = 0; i < 50; i++) {
  utils.javaInstantToJsInstant(ins)
}

var end = time.Instant.now().toEpochMilli();
console.log('Benchmark finshed, took ' + (end - start) + ' ms')

var ZonedDateTime = Java.type('java.time.ZonedDateTime');
var zdt = ZonedDateTime.now();

console.log('Benchmarking ZonedDateTime.parse conversion ...')
var start = time.Instant.now().toEpochMilli();

for (var i = 0; i < 50; i++) {
  time.ZonedDateTime.parse(zdt.toString())
}

var end = time.Instant.now().toEpochMilli();
console.log('Benchmark finshed, took ' + (end - start) + ' ms')

console.log('Benchmarking advanced ZonedDateTime conversion ...')
var start = time.Instant.now().toEpochMilli();

for (var i = 0; i < 50; i++) {
  utils.javaZDTToJsZDT(zdt)
}

var end = time.Instant.now().toEpochMilli();
console.log('Benchmark finshed, took ' + (end - start) + ' ms')

gives:

15:01:37.711 [INFO ] [penhab.automation.script.file.test.js] - Benchmarking Instant.parse conversion ...
15:01:37.773 [INFO ] [penhab.automation.script.file.test.js] - Benchmark finshed, took 61 ms
15:01:37.774 [INFO ] [penhab.automation.script.file.test.js] - Benchmarking advanced Instant conversion ...
15:01:37.777 [INFO ] [penhab.automation.script.file.test.js] - Benchmark finshed, took 2 ms
15:01:37.777 [INFO ] [penhab.automation.script.file.test.js] - Benchmarking ZonedDateTime.parse conversion ...
15:01:37.947 [INFO ] [penhab.automation.script.file.test.js] - Benchmark finshed, took 170 ms
15:01:37.947 [INFO ] [penhab.automation.script.file.test.js] - Benchmarking advanced ZonedDateTime conversion ...
15:01:37.969 [INFO ] [penhab.automation.script.file.test.js] - Benchmark finshed, took 21 ms