[{"data":1,"prerenderedAt":76},["ShallowReactive",2],{"course-en-performance":3},{"lesson":4,"number":67,"prev":68,"next":72},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":37,"exercises":48},"performance",{"ru":7,"en":8},"","Performance",{"ru":7,"en":10},"Where the performance gap between functional JavaScript and a for loop comes from, why one measurement proves nothing, and when imperative code is worth it.",{"ru":7,"en":12},"Understand where the speed difference between functional and imperative code comes from, why a single measurement proves nothing, and when it is worth switching to low-level imperative tools.",[14,17,19,21,23,25,29,31,33],{"type":15,"ru":7,"en":16},"text","It is worth noting that in microbenchmarks an imperative loop can be several times faster, but in absolute terms the difference is usually negligible. Sometimes functional code can even show the same or better results thanks to optimizations in the JavaScript engine. If maintainability, reliability, and a sound architecture are on one side of the scales, then functional code is undoubtedly the better choice.",{"type":15,"ru":7,"en":18},"Improving the speed of functional code is primarily the responsibility of the developers of JavaScript engines. That is, engine developers carry out improvements and optimizations of the compiler and the garbage collector.",{"type":15,"ru":7,"en":20},"Every abstraction introduces a small additional resource cost, which is often not critical.",{"type":15,"ru":7,"en":22},"In projects where speed is critical and the number of elements reaches several tens of thousands or even hundreds of thousands during synchronous execution, and we cannot spawn a separate thread due to a lack of hardware resources — namely a free CPU core — we can resort to low-level imperative tools.",{"type":15,"ru":7,"en":24},"In 98% of cases the performance of your application is determined more by the correct logic of how the program is built than by an extra abstraction.",{"type":26,"code":27},"code",{"ru":7,"en":28},"\u002F\u002F Let's take a few small measurements\n\u002F\u002F ===============================\n\u002F\u002F a function that generates an array of numbers from 1 to n inclusive\n\u002F\u002F createNumberArray :: Number -> [Number]\nconst createNumberArray = (n) => new Array(n).fill(1).map((_, i) => i + 1)\n\n\u002F\u002F a function that sums the numbers in an array declaratively\n\u002F\u002F sumD :: [Number] -> Number\nconst sumD = (arr) => arr.reduce((acc, curr) => acc + curr)\n\n\u002F\u002F a function that sums the numbers in an array imperatively\nconst sumN = (arr) => {\n  let result = 0\n  const length = arr.length\n\n  for (let i = 0; i \u003C length; i += 1) {\n    result = result + arr[i]\n  }\n\n  return result\n}\n\u002F\u002F ===============================\n\n\u002F\u002F let's start testing\n\u002F\u002F ===============================\n\u002F\u002F create the data: an array of 100,000 numbers\nconst dataNumber = createNumberArray (100000)\n\n\u002F\u002F timing the declarative code\n\u002F\u002F ===============================\nconst startT = performance.now() \u002F\u002F start time\nconst resultD = sumD (dataNumber) \u002F\u002F the code being measured\nconst endT = performance.now() \u002F\u002F end time\n\n\u002F\u002F compute the delta and log it\nconsole.log('Declarative code run time: ' + (endT - startT) + ' milliseconds. Result: ' + resultD)\n\u002F\u002F the run time of course depends on your device and on how warmed up the hardware is\n\u002F\u002F this test is not very precise\n\u002F\u002F the main thing here is to catch the difference between imperative and declarative code\n\u002F\u002F 2.4274640000000005 milliseconds. Result: 5000050000\n\u002F\u002F ===============================\n\n\u002F\u002F it's better to run the second measurement separately, not right after the first one\n\n\u002F\u002F timing the imperative code\n\u002F\u002F ===============================\nconst startI = performance.now() \u002F\u002F start time\nconst resultI = sumN (dataNumber) \u002F\u002F the code being measured\nconst endI = performance.now() \u002F\u002F end time\n\n\u002F\u002F compute the delta and log it\nconsole.log('Imperative code run time: ' + (endI - startI) + ' milliseconds. Result: ' + resultI)\n\u002F\u002F the run time of course depends on your device and on how warmed up the hardware is\n\u002F\u002F the main thing here is to catch the difference between imperative and declarative code\n\u002F\u002F 2.2674640000000005 milliseconds. Result: 5000050000\n\u002F\u002F 2.380783000000008 milliseconds. Result: 5000050000\n\u002F\u002F 2.600783000000008 milliseconds. Result: 5000050000\n\u002F\u002F ===============================\n\n\u002F\u002F The times came out close, and from run to run\n\u002F\u002F either version may come out ahead\n\u002F\u002F In a single measurement the engine hasn't warmed up and optimized the code yet,\n\u002F\u002F and the garbage collector and background tasks affect the time\n\u002F\u002F So you can't draw conclusions from one measurement: you need repetitions",{"type":15,"ru":7,"en":30},"A single measurement like this proves nothing: the difference is within the margin of error. For a fairer comparison, call the function many times and average the time.",{"type":15,"ru":7,"en":32},"Let's write a small utility for measurements and run some execution-speed tests.",{"type":26,"noRun":34,"code":35},"previous-block",{"ru":7,"en":36},"\u002F\u002F Speed measurement utility\n\u002F\u002F createNumberArray, sumN and sumD come from the previous block,\n\u002F\u002F so run this block together with it\n\u002F\u002F ===============================\nconst benchmark = (fn) => (n = 100) => (msg = '') => {\n  \u002F\u002F running total of the measured time\n  let total = 0\n\n  \u002F\u002F number of times we call our function\n  for (let i = 0; i \u003C n; i++) {\n    \u002F\u002F take the start time before the call\n    const start = performance.now()\n\n    \u002F\u002F call the function\n    fn()\n\n    \u002F\u002F add the difference between the end and start times\n    total += performance.now() - start\n  }\n\n  console.log(msg) \u002F\u002F log message\n\n  \u002F\u002F then divide the total time by the number of calls\n  \u002F\u002F and return the arithmetic mean\n  return total \u002F n\n}\n\n\u002F\u002F let's create two functions\n\u002F\u002F for working with an array of numbers\n\u002F\u002F preparing the data\n\u002F\u002F ======================\n\u002F\u002F array of numbers 1 - 100,000\nconst dataNumbers = createNumberArray (100000)\n\n\u002F\u002F a wrapper for the imperative function\n\u002F\u002F and the declarative function\n\u002F\u002F sumWrap :: ([Number] -> Number) -> [Number] -> (() -> Number)\nconst sumWrap = (fn) => (arr) => () => fn(arr)\n\n\u002F\u002F imperative summing function\nconst sumImperative = sumWrap (sumN) (dataNumbers)\n\n\u002F\u002F declarative summing function\nconst sumDeclarative = sumWrap (sumD) (dataNumbers)\n\n\u002F\u002F Note: don't run both functions at the same time\n\u002F\u002F run one first, and then the second one some time later\n\n\u002F\u002F measuring the imperative function\nconst resultImperative = benchmark (sumImperative) (1000) ('measurement finished')\nconsole.log (resultImperative) \u002F\u002F 0.15482687300000053\n\u002F\u002F measuring the declarative function\nconst resultDeclarative = benchmark (sumDeclarative) (1000) ('measurement finished')\nconsole.log (resultDeclarative) \u002F\u002F 1.2971963320000012\n\n\u002F\u002F in this measurement the imperative loop turned out several times faster than reduce\n\u002F\u002F the reason is overhead: reduce calls a callback function for every element,\n\u002F\u002F while each step of the for loop is just a comparison and an addition,\n\u002F\u002F which the engine turns into compact machine code\n\u002F\u002F engines can partly remove this overhead, so the difference depends\n\u002F\u002F on the engine, its version and the data: a microbenchmark is a guide, not a law\n\u002F\u002F in absolute terms, in the measurement above it's about a millisecond per 100,000 elements:\n\u002F\u002F noticeable in hot code that runs many times, but usually not elsewhere",[38,40,42,44,46],{"ru":7,"en":39},"In microbenchmarks an imperative loop can be several times faster, but in absolute terms the difference is usually negligible.",{"ru":7,"en":41},"Every abstraction adds a small resource cost: for example, reduce calls a callback function for every element, while a for loop only compares and adds.",{"ru":7,"en":43},"You can't draw conclusions from a single measurement: call the function many times and average the time.",{"ru":7,"en":45},"In 98% of cases the speed of an application depends more on the correct logic of how the program is built than on an extra abstraction.",{"ru":7,"en":47},"Low-level imperative tools are for cases where speed is critical, there are tens or hundreds of thousands of elements, and the computation cannot be moved to a separate thread.",[49,58],{"task":50,"starter":52,"solution":54,"expected":56},{"ru":7,"en":51},"Without measuring time, see where the overhead of abstractions comes from. In the starter, the sum of the squares of the even numbers from 1 to 1000 is computed with a chain of filter, map and reduce, and the counter wrapper counts the callback calls. Compute the same thing with a single reduce, also through counter, and compare the result and the number of calls.",{"ru":7,"en":53},"\u002F\u002F counter counts the calls of the functions wrapped with wrap\n\u002F\u002F counter :: () -> Object\nconst counter = () => {\n  let calls = 0\n  return {\n    wrap: (fn) => (...args) => {\n      calls += 1\n      return fn(...args)\n    },\n    calls: () => calls,\n  }\n}\n\n\u002F\u002F createNumberArray from the lesson: the numbers from 1 to n\n\u002F\u002F createNumberArray :: Number -> [Number]\nconst createNumberArray = (n) => new Array(n).fill(1).map((_, i) => i + 1)\n\nconst numbers = createNumberArray(1000)\n\n\u002F\u002F the chain: three passes and two intermediate arrays\nconst chain = counter()\nconst chainResult = numbers\n  .filter(chain.wrap((n) => n % 2 === 0))\n  .map(chain.wrap((n) => n * n))\n  .reduce(chain.wrap((acc, n) => acc + n), 0)\n\nconsole.log('chain: ' + chainResult + ', calls: ' + chain.calls())\n\n\u002F\u002F a single pass\nconst single = counter()\n\u002F\u002F your code: the same sum with a single reduce, its callback wrapped in single.wrap\nconst singleResult = 0\n\nconsole.log('single reduce: ' + singleResult + ', calls: ' + single.calls())",{"ru":7,"en":55},"\u002F\u002F counter counts the calls of the functions wrapped with wrap\n\u002F\u002F counter :: () -> Object\nconst counter = () => {\n  let calls = 0\n  return {\n    wrap: (fn) => (...args) => {\n      calls += 1\n      return fn(...args)\n    },\n    calls: () => calls,\n  }\n}\n\n\u002F\u002F createNumberArray from the lesson: the numbers from 1 to n\n\u002F\u002F createNumberArray :: Number -> [Number]\nconst createNumberArray = (n) => new Array(n).fill(1).map((_, i) => i + 1)\n\nconst numbers = createNumberArray(1000)\n\n\u002F\u002F the chain: three passes and two intermediate arrays\nconst chain = counter()\nconst chainResult = numbers\n  .filter(chain.wrap((n) => n % 2 === 0))\n  .map(chain.wrap((n) => n * n))\n  .reduce(chain.wrap((acc, n) => acc + n), 0)\n\nconsole.log('chain: ' + chainResult + ', calls: ' + chain.calls())\n\n\u002F\u002F a single pass: the check, the square and the addition in one callback\nconst single = counter()\nconst singleResult = numbers.reduce(\n  single.wrap((acc, n) => (n % 2 === 0 ? acc + n * n : acc)),\n  0,\n)\n\nconsole.log('single reduce: ' + singleResult + ', calls: ' + single.calls())\n\n\u002F\u002F the result is the same, with half the calls and no intermediate arrays,\n\u002F\u002F but the chain is easier to read; on 1000 elements the difference is invisible,\n\u002F\u002F and merging the steps into one reduce makes sense in hot code",{"ru":7,"en":57},"chain: 167167000, calls: 2000\nsingle reduce: 167167000, calls: 1000",{"task":59,"starter":61,"solution":63,"expected":65},{"ru":7,"en":60},"The lesson says that speed depends more often on the program's logic than on an extra abstraction. In the starter, the customer name for each of 1000 orders is looked up with users.find, which scans the users array again for every order. Rewrite it so that the users are collected once with reduce into an object keyed by id, and the name is taken from that object. Compare the number of callback calls and check that the result is the same.",{"ru":7,"en":62},"\u002F\u002F counter counts the calls of the functions wrapped with wrap\n\u002F\u002F counter :: () -> Object\nconst counter = () => {\n  let calls = 0\n  return {\n    wrap: (fn) => (...args) => {\n      calls += 1\n      return fn(...args)\n    },\n    calls: () => calls,\n  }\n}\n\n\u002F\u002F createNumberArray from the lesson: the numbers from 1 to n\n\u002F\u002F createNumberArray :: Number -> [Number]\nconst createNumberArray = (n) => new Array(n).fill(1).map((_, i) => i + 1)\n\n\u002F\u002F 1000 users and 1000 orders: order 1 was placed by user 1000, and so on\nconst users = createNumberArray(1000).map((id) => ({ id, name: 'user' + id }))\nconst orders = createNumberArray(1000).map((id) => ({ id, userId: 1001 - id }))\n\n\u002F\u002F scanning: for every order find walks the users array again\nconst scan = counter()\nconst withNamesScan = orders.map(\n  scan.wrap((order) => ({\n    ...order,\n    userName: users.find(scan.wrap((user) => user.id === order.userId)).name,\n  })),\n)\n\nconsole.log('scan: ' + scan.calls() + ' calls')\n\n\u002F\u002F an index\nconst index = counter()\n\u002F\u002F your code: usersById with reduce, then withNamesIndex with map,\n\u002F\u002F the callbacks wrapped in index.wrap\nconst withNamesIndex = []\n\nconsole.log('index: ' + index.calls() + ' calls')\nconsole.log('same result: ' + (JSON.stringify(withNamesScan) === JSON.stringify(withNamesIndex)))",{"ru":7,"en":64},"\u002F\u002F counter counts the calls of the functions wrapped with wrap\n\u002F\u002F counter :: () -> Object\nconst counter = () => {\n  let calls = 0\n  return {\n    wrap: (fn) => (...args) => {\n      calls += 1\n      return fn(...args)\n    },\n    calls: () => calls,\n  }\n}\n\n\u002F\u002F createNumberArray from the lesson: the numbers from 1 to n\n\u002F\u002F createNumberArray :: Number -> [Number]\nconst createNumberArray = (n) => new Array(n).fill(1).map((_, i) => i + 1)\n\n\u002F\u002F 1000 users and 1000 orders: order 1 was placed by user 1000, and so on\nconst users = createNumberArray(1000).map((id) => ({ id, name: 'user' + id }))\nconst orders = createNumberArray(1000).map((id) => ({ id, userId: 1001 - id }))\n\n\u002F\u002F scanning: for every order find walks the users array again\nconst scan = counter()\nconst withNamesScan = orders.map(\n  scan.wrap((order) => ({\n    ...order,\n    userName: users.find(scan.wrap((user) => user.id === order.userId)).name,\n  })),\n)\n\nconsole.log('scan: ' + scan.calls() + ' calls')\n\n\u002F\u002F an index: a single reduce pass builds an object keyed by user id\nconst index = counter()\nconst usersById = users.reduce(\n  index.wrap((acc, user) => {\n    acc[user.id] = user\n    return acc\n  }),\n  {},\n)\nconst withNamesIndex = orders.map(\n  index.wrap((order) => ({ ...order, userName: usersById[order.userId].name })),\n)\n\nconsole.log('index: ' + index.calls() + ' calls')\nconsole.log('same result: ' + (JSON.stringify(withNamesScan) === JSON.stringify(withNamesIndex)))\n\n\u002F\u002F both versions are declarative: the difference comes from the logic,\n\u002F\u002F one pass instead of a scan for every order, not from dropping abstractions",{"ru":7,"en":66},"scan: 501500 calls\nindex: 2000 calls\nsame result: true",15,{"slug":69,"title":70},"function-map-filter-reduce",{"ru":7,"en":71},"The map, filter, and reduce functions",{"slug":73,"title":74},"memoization",{"ru":7,"en":75},"Memoization",1792684725054]