var n = 1000000
var arr = new Array(n)
for(var i = 0; i < n; i++){
arr[i] = i
}
class Observer {
constructor() {
this.value = 0
this.completed = false
}
next (val) {
this.value+=val
}
complete () {
this.completed = true
}
}
class FromDirect {
constructor (arr) {
this.array = arr
}
sum (observer) {
for (var i = 0; i < this.array.length; ++i) {
observer.next(this.array[i])
}
observer.complete()
}
}
class FromLater {
constructor (arr) {
this.array = arr
}
sum (observer) {
for (var i = 0; i < this.array.length; ++i) {
observer.next(this.array[i])
}
end()
function end () {
observer.complete()
}
}
}
var Ob0 = new Observer()
var Ob1 = new Observer()
var t0 = new FromDirect(arr)
t0.sum(Ob0)
var t1 = new FromLater(arr)
t1.sum(Ob1)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Direct Call | |
Later Call |
Test name | Executions per second |
---|---|
Direct Call | 222.3 Ops/sec |
Later Call | 211.6 Ops/sec |
Overview
The provided JSON represents a JavaScript benchmarking test case for measuring the performance of two different approaches to calling a function: direct call and later call. The test compares the execution time of these two approaches on an array of 1 million elements.
Benchmark Definition
The benchmark definition is composed of three main parts:
arr
with 1 million elements, initialized with incremental values from 0 to 999,999.Observer
and its subclasses FromDirect
and FromLater
. These observers are used to track the value of an object's property value
.sum
that takes an observer as an argument and iterates over the array, calling the next
method on the observer for each element.Test Cases
The test consists of two individual test cases:
sum
function directly on an instance of FromDirect
, passing an observer instance as an argument.sum
function later, passing an observer instance as an argument.Options Compared
The benchmark compares the execution time of two approaches:
sum
function immediately, passing the observer instance as an argument.sum
function later, using a separate function to update the observer's completed
property when the iteration is complete.Pros and Cons
completed
property needs to be updated only after all iterations are complete.Library and Its Purpose
The Observer
class is a simple implementation of the Observer pattern, which allows objects to notify other objects about changes to their state. In this context, it is used to track the value of an object's property value
.
Special JS Feature or Syntax
There are no special JavaScript features or syntaxes used in this benchmark.
Alternatives
Other alternatives for implementing the Observer
pattern include:
Note that these alternatives may offer different trade-offs in terms of complexity, performance, and readability.