[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"verticals":3,"quiz-resizable-arraybuffer-transfer":44,"search-suggestions":60,"quiz-article-resizable-arraybuffer-transfer":109,"path-membership-resizable-arraybuffer-transfer":311},[4,20,32],{"id":5,"slug":6,"name":7,"tagline":8,"description":9,"accentFrom":10,"accentTo":11,"icon":12,"defaultLocale":13,"locales":14,"features":16,"position":19},"019fe637-3d33-714b-b57f-23e163ffca0c","dev","Web Development","Read it. Run it. Prove it.","A post a day on modern web development — most with an editable playground and a quiz that explains every answer. Free, no account needed.","violet-500","cyan-400","◇","en",[13,15],"fa",{"courses":17,"paths":17,"articles":17,"exams":18,"flashcards":18,"packages":17,"community":17,"certificates":17,"teams":17,"commerce":17},true,false,0,{"id":21,"slug":22,"name":23,"tagline":24,"description":25,"accentFrom":26,"accentTo":10,"icon":27,"defaultLocale":13,"locales":28,"features":30,"position":31},"019fe637-3dc2-754c-8657-0f175bfee7c6","lang","Languages","Learn a language the way you learn a codebase.","Grammar explained the way good documentation explains an API — one idea at a time, each with a quiz.","amber-400","⌘",[13,15,29],"es",{"courses":18,"paths":18,"articles":17,"exams":18,"flashcards":17,"packages":18,"community":17,"certificates":17,"teams":18,"commerce":18},2,{"id":33,"slug":34,"name":35,"tagline":36,"description":37,"accentFrom":38,"accentTo":39,"icon":40,"defaultLocale":13,"locales":41,"features":42,"position":43},"7b3c16f2-931d-410e-802e-e1fa4edab7de","soft","Soft Skills","The half of the job nobody wrote documentation for.","Weekly, on the parts of working life that decide more than your code does — first weeks, meetings, interviews, promotions, and the people around you. Written from what actually happens, and recorded as a podcast you can listen to on the walk.","emerald-400","teal-300","◉",[13],{"courses":18,"paths":18,"articles":17,"exams":18,"flashcards":18,"packages":18,"community":17,"certificates":18,"teams":18,"commerce":18},3,{"id":45,"slug":46,"kind":47,"title":48,"description":49,"config":50,"verticalId":5,"vertical":55,"course":52,"_count":56,"access":57,"attempts":59,"questionCount":51},"01a21cc5-6ada-701b-b9ef-4aaf15fd8c6c","resizable-arraybuffer-transfer","PRACTICE_QUIZ","Resizable ArrayBuffer & transfer() — Test Yourself","Six questions on growing a buffer in place versus the old allocate-and-copy dance, and on what transfer() actually changes about handing a buffer off.",{"questionCount":51,"timeLimitSec":52,"shuffleQuestions":18,"shuffleOptions":17,"negativeMarking":19,"passScorePct":53,"maxAttempts":52,"revealAnswers":54,"allowFlagging":18,"allowBacktracking":17},6,null,70,"AFTER_SUBMIT",{"slug":6,"name":7},{"questions":51},{"allowed":17,"reason":58},"FREE",[],[61,65,69,73,77,81,85,89,93,97,101,105],{"slug":62,"name":63,"articles":64},"webdev","Webdev",200,{"slug":66,"name":67,"articles":68},"javascript","Javascript",158,{"slug":70,"name":71,"articles":72},"frontend","Frontend",105,{"slug":74,"name":75,"articles":76},"tutorial","Tutorial",90,{"slug":78,"name":79,"articles":80},"css","Css",58,{"slug":82,"name":83,"articles":84},"typescript","Typescript",37,{"slug":86,"name":87,"articles":88},"performance","Performance",34,{"slug":90,"name":91,"articles":92},"programming","Programming",26,{"slug":94,"name":95,"articles":96},"react","React",23,{"slug":98,"name":99,"articles":100},"node","Node",19,{"slug":102,"name":103,"articles":104},"browser","Browser",18,{"slug":106,"name":107,"articles":108},"nextjs","Nextjs",14,{"id":110,"slug":46,"title":111,"subtitle":52,"excerpt":112,"coverUrl":113,"locale":13,"readingMinutes":114,"publishedAt":115,"viewCount":51,"likeCount":19,"commentCount":19,"author":116,"vertical":121,"topic":122,"tags":124,"_count":129,"playground":131,"body":133,"bodyMd":297,"seo":298,"translationGroupId":301,"series":52,"podcastUrl":52,"verticalId":5,"thread":302,"assessments":304,"translations":307,"quiz":309},"01a21cc5-6a9e-740d-b36d-cfa2c70b74e2","I Kept Copying Buffers to Grow Them. Resizable ArrayBuffer Fixed It.","Every \"growable buffer\" helper allocates bigger, copies everything in, and throws the old buffer away — on a 200MB export that copy is a visible stutter. Resizable ArrayBuffer grows in place, and transfer() hands off ownership without a copy or a postMessage side effect.","\u002Fmedia\u002Fcovers\u002Fresizable-arraybuffer-transfer.png",7,"2026-12-02T12:03:44.541Z",{"id":117,"name":118,"username":119,"avatarUrl":52,"headline":120},"019fe637-3c25-7088-9034-39c9f15dc3c8","Parsa Jiravand","parsa","Frontend engineer · building bestpractic",{"slug":6,"name":7,"accentFrom":10,"accentTo":11},{"slug":66,"name":123},"JavaScript",[125,126,127,128],{"slug":66,"name":67,"color":52},{"slug":62,"name":63,"color":52},{"slug":86,"name":87,"color":52},{"slug":74,"name":75,"color":52},{"assessments":130},1,{"slug":46,"title":132},"resizable ArrayBuffer — interactive playground",{"blocks":134,"version":130},[135,139,142,146,149,155,158,161,164,167,170,173,177,180,183,186,189,192,195,198,202,205,209,212,215,219,222,225,229,232,235,238,241,244,248,251,254,257,260,263,266,269,272,279,282,285,288,291],{"id":136,"html":137,"type":138},"b1","\u003Cp>The &quot;export everything&quot; button had been fine for months. Then someone with eighteen months of notes in the app hit it, and the progress bar started hitching — not failing, just stuttering, every few seconds, like clockwork.\u003C\u002Fp>","paragraph",{"id":140,"html":141,"type":138},"b2","\u003Cp>No errors in the console. No dropped frames in a \u003Cem>normal\u003C\u002Fem> sense. Just a build-up feature that got measurably janky exactly in proportion to how much data someone had.\u003C\u002Fp>",{"id":143,"html":144,"text":144,"type":145,"level":31},"b3","The buffer builder every binary export reaches for","heading",{"id":147,"html":148,"type":138},"b4","\u003Cp>The export assembles a single file from chunks — attachments, encoded notes, whatever — arriving over time from IndexedDB, in pieces whose total size you don&#39;t know up front. The standard fix for &quot;I need one contiguous buffer but don&#39;t know the final size&quot; looks like this:\u003C\u002Fp>",{"id":150,"code":151,"type":152,"language":153,"highlight":154},"b5","function createGrowableBuffer(initialCapacity = 4096) {\n  let buffer = new ArrayBuffer(initialCapacity);\n  let view = new Uint8Array(buffer);\n  let length = 0;\n\n  function append(bytes) {\n    if (length + bytes.length > buffer.byteLength) {\n      const bigger = new ArrayBuffer(Math.max(buffer.byteLength * 2, length + bytes.length));\n      new Uint8Array(bigger).set(view.subarray(0, length));\n      buffer = bigger;\n      view = new Uint8Array(buffer);\n    }\n    view.set(bytes, length);\n    length += bytes.length;\n  }\n\n  return { append, bytes: () => view.subarray(0, length) };\n}","code","js",[],{"id":156,"html":157,"type":138},"b6","\u003Cp>This is the pattern you&#39;ll find in most hand-rolled binary buffer builders, and it isn&#39;t wrong, exactly — doubling capacity is the standard amortized-growth trick, the same one \u003Ccode>Array\u003C\u002Fcode>, \u003Ccode>String\u003C\u002Fcode> concatenation, and \u003Ccode>Vec\u003C\u002Fcode> in other languages all use internally. It&#39;s also exactly why this one stutters.\u003C\u002Fp>",{"id":159,"html":160,"type":138},"b7","\u003Cp>\u003Cstrong>Before you keep reading: what does every call to \u003Ccode>append\u003C\u002Fcode> actually cost, once the buffer is full?\u003C\u002Fstrong>\u003C\u002Fp>",{"id":162,"html":163,"type":138},"b8","\u003Cp>A brand-new \u003Ccode>ArrayBuffer\u003C\u002Fcode>, allocated at double the size, and a full copy of \u003Cem>every byte appended so far\u003C\u002Fem> into it — then the old buffer becomes garbage. Early on that&#39;s nothing: copying 8KB is instant. But capacity doubles each time, so the copies get bigger exactly as the export gets bigger. On a 200MB file built from 4KB chunks, the last couple of growth steps are each copying 50-100MB on the main thread, synchronously, in one \u003Ccode>memcpy\u003C\u002Fcode>-sized function call that blocks everything else — a single-threaded \u003Ccode>set()\u003C\u002Fcode> call doesn&#39;t yield partway through. That&#39;s the stutter: not a bug, just the doubling trick doing exactly what it&#39;s designed to do, at a size where &quot;exactly what it&#39;s designed to do&quot; is expensive.\u003C\u002Fp>",{"id":165,"html":166,"text":166,"type":145,"level":31},"b9","Growing used to mean allocating somewhere else",{"id":168,"html":169,"type":138},"b10","\u003Cp>The real constraint was never the algorithm — it&#39;s that a regular \u003Ccode>ArrayBuffer\u003C\u002Fcode> is a fixed-size, fixed-location block of memory from the moment it&#39;s created. &quot;Growing&quot; one has only ever meant \u003Cem>creating a different, bigger one\u003C\u002Fem> and copying into it, because the original can&#39;t get bigger where it already lives.\u003C\u002Fp>",{"id":171,"html":172,"type":138},"b11","\u003Cp>As of mid-2024, that&#39;s no longer the only option. \u003Ccode>ArrayBuffer\u003C\u002Fcode> can now be created resizable, with a declared ceiling:\u003C\u002Fp>",{"id":174,"code":175,"type":152,"language":153,"highlight":176},"b12","function createGrowableBuffer(initialCapacity = 4096, maxCapacity = 512 * 1024 * 1024) {\n  const buffer = new ArrayBuffer(initialCapacity, { maxByteLength: maxCapacity });\n  const view = new Uint8Array(buffer); \u002F\u002F no offset\u002Flength given → tracks the buffer's size automatically\n  let length = 0;\n\n  function append(bytes) {\n    if (length + bytes.length > buffer.byteLength) {\n      buffer.resize(Math.min(maxCapacity, Math.max(buffer.byteLength * 2, length + bytes.length)));\n    }\n    view.set(bytes, length);\n    length += bytes.length;\n  }\n\n  return { append, bytes: () => view.subarray(0, length) };\n}",[],{"id":178,"html":179,"type":138},"b13","\u003Cp>\u003Ccode>buffer.resize()\u003C\u002Fcode> grows (or shrinks) the \u003Cem>same\u003C\u002Fem> allocation — no new \u003Ccode>ArrayBuffer\u003C\u002Fcode>, no copy of the existing bytes, no garbage for the collector to clean up later. The \u003Ccode>Uint8Array\u003C\u002Fcode> built without an explicit length is &quot;length-tracking&quot;: it automatically reflects however big the underlying buffer currently is, so there&#39;s no need to rebuild the view after every resize the way the old version had to.\u003C\u002Fp>",{"id":181,"html":182,"type":138},"b14","\u003C!-- playground:start -->",{"id":184,"html":185,"text":185,"type":145,"level":31},"b15","🎮 Try it yourself",{"id":187,"html":188,"type":138},"b16","\u003Cp>\u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fresizable-arraybuffer-transfer\u002Fplayground\">▶️ Open the interactive playground →\u003C\u002Fa>\u003C\u002Fstrong>\u003C\u002Fp>",{"id":190,"html":191,"type":138},"b17","\u003Cp>\u003Cem>Runs right in your browser — poke at it and watch the concept react live.\u003C\u002Fem>\u003C\u002Fp>",{"id":193,"html":194,"type":138},"b18","\u003C!-- playground:end -->",{"id":196,"html":197,"type":138},"b19","\u003Cp>The ceiling is real, not a suggestion — ask it to grow past \u003Ccode>maxByteLength\u003C\u002Fcode> and it refuses:\u003C\u002Fp>",{"id":199,"code":200,"type":152,"language":153,"highlight":201},"b20","const buffer = new ArrayBuffer(1024, { maxByteLength: 4096 });\nbuffer.resize(8192); \u002F\u002F throws — 8192 is past the 4096 you declared up front",[],{"id":203,"html":204,"type":138},"b21","\u003Cp>You have to decide the maximum size up front, the same way you&#39;d pass a capacity hint to a \u003Ccode>Vec\u003C\u002Fcode> or a \u003Ccode>StringBuilder\u003C\u002Fcode> in another language. For the export button, that&#39;s &quot;how big could this reasonably ever get&quot; — a few hundred MB, say — not an unbounded number. That&#39;s a feature, not friction: a buffer that could grow to fill all of memory because nobody set a ceiling is its own bug.\u003C\u002Fp>",{"id":206,"html":207,"text":208,"type":145,"level":31},"b22","The second bug the fix didn&#39;t know it was also fixing","The second bug the fix didn't know it was also fixing",{"id":210,"html":211,"type":138},"b23","\u003Cp>There was a second, stranger report buried in the same feature: occasionally, a background &quot;compress before download&quot; step — handed off to a worker — would silently produce an empty file. Not an error. Just zero bytes, like the buffer had never had anything in it.\u003C\u002Fp>",{"id":213,"html":214,"type":138},"b24","\u003Cp>The cause was a few files away from the compression code: a different part of the export flow held a reference to the same raw buffer and had already posted it to \u003Cem>another\u003C\u002Fem> worker as a transferable:\u003C\u002Fp>",{"id":216,"code":217,"type":152,"language":153,"highlight":218},"b25","worker.postMessage(rawBuffer, [rawBuffer]);\n\u002F\u002F elsewhere, no error, no warning:\nconsole.log(rawBuffer.byteLength); \u002F\u002F 0",[],{"id":220,"html":221,"type":138},"b26","\u003Cp>\u003Ccode>postMessage\u003C\u002Fcode>&#39;s transfer list has always worked this way — listing an \u003Ccode>ArrayBuffer\u003C\u002Fcode> there \u003Cem>detaches\u003C\u002Fem> it from the sender, handing the actual memory to the receiver with no copy. That&#39;s efficient, and it&#39;s also completely invisible at the call site that gets bitten by it: nothing about \u003Ccode>console.log(rawBuffer.byteLength)\u003C\u002Fcode> looks wrong, three files away from the \u003Ccode>postMessage\u003C\u002Fcode> call that zeroed it out.\u003C\u002Fp>",{"id":223,"html":224,"type":138},"b27","\u003Cp>\u003Ccode>ArrayBuffer.prototype.transfer()\u003C\u002Fcode> does the same ownership hand-off, but as a method you call directly, anywhere — not only across a \u003Ccode>postMessage\u003C\u002Fcode> boundary:\u003C\u002Fp>",{"id":226,"code":227,"type":152,"language":153,"highlight":228},"b28","function handOff(buffer) {\n  const owned = buffer.transfer(); \u002F\u002F new ArrayBuffer, same bytes where possible, no copy\n  console.log(buffer.detached); \u002F\u002F true — immediately, at the call site that caused it\n  return owned;\n}\n\nconst exported = handOff(rawBuffer);\nworker.postMessage(exported, [exported]);",[],{"id":230,"html":231,"type":138},"b29","\u003Cp>Nothing here is new memory-safety machinery — detaching a buffer and handing its bytes to a new owner is exactly what the transfer list already did. What&#39;s new is that it&#39;s no longer something that only happens as a side effect of the second argument to \u003Ccode>postMessage\u003C\u002Fcode>. \u003Ccode>buffer.transfer()\u003C\u002Fcode> reads, in the code that calls it, as &quot;I am done owning this&quot; — so when something downstream still expects \u003Ccode>rawBuffer\u003C\u002Fcode> to have bytes in it, the bug is one \u003Ccode>grep\u003C\u002Fcode> away from the line that changed it, not a fact about a worker boundary you have to hold in your head.\u003C\u002Fp>",{"id":233,"html":234,"type":138},"b30","\u003Cp>(If you need the result to definitely \u003Cem>not\u003C\u002Fem> be resizable afterward — handing a buffer off to code that assumes a fixed size — \u003Ccode>transferToFixedLength()\u003C\u002Fcode> does the same move and strips the resizability.)\u003C\u002Fp>",{"id":236,"html":237,"text":237,"type":145,"level":31},"b31","What the export looks like now",{"id":239,"html":240,"type":138},"b32","\u003Cp>The buffer builder resizes in place instead of reallocating, so the stutter that scaled with export size is gone — there&#39;s no longer a growth step that costs a 100MB copy, because there&#39;s no copy at all. And the empty-download bug turned into something \u003Ccode>grep\u003C\u002Fcode>-able: every place a buffer changes hands now says so, in a method name, instead of hiding in a transfer list.\u003C\u002Fp>",{"id":242,"html":243,"type":138},"b33","\u003Cp>Neither fix needed a library. \u003Ccode>resize()\u003C\u002Fcode>, \u003Ccode>transfer()\u003C\u002Fcode>, and the \u003Ccode>maxByteLength\u003C\u002Fcode> option are Baseline — newly available across Chrome, Firefox, and Safari since 2024 (\u003Ccode>transfer()\u003C\u002Fcode> reached Baseline first, in March 2024; resizable buffers followed that July, once Firefox shipped \u003Ccode>resize()\u003C\u002Fcode> too) — so if your target browsers are current, this is just how \u003Ccode>ArrayBuffer\u003C\u002Fcode> works now. If you still support something older, feature-detect before you lean on it:\u003C\u002Fp>",{"id":245,"code":246,"type":152,"language":153,"highlight":247},"b34","const hasResizableBuffers = typeof ArrayBuffer.prototype.resize === \"function\";",[],{"id":249,"html":250,"type":138},"b35","\u003Cp>If you&#39;ve got a doubling-buffer builder living in a binary parser or an export feature somewhere, it&#39;s probably not causing a problem yet — it&#39;s just waiting for someone with enough data to feel the copy. Have you been bitten by a buffer that went quietly empty after a \u003Ccode>postMessage\u003C\u002Fcode> call you weren&#39;t looking at?\u003C\u002Fp>",{"id":252,"html":253,"type":138},"b36","\u003C!-- quiz:start -->",{"id":255,"html":256,"text":256,"type":145,"level":31},"b37","🧠 Test yourself",{"id":258,"html":259,"type":138},"b38","\u003Cp>Think it clicked? \u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fresizable-arraybuffer-transfer\u002Fquiz\">Take the 6-question quiz →\u003C\u002Fa>\u003C\u002Fstrong>\u003C\u002Fp>",{"id":261,"html":262,"type":138},"b39","\u003Cp>\u003Cem>Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.\u003C\u002Fem>\u003C\u002Fp>",{"id":264,"html":265,"type":138},"b40","\u003C!-- quiz:end -->",{"id":267,"html":268,"type":138},"b41","\u003C!-- related:start -->",{"id":270,"html":271,"text":271,"type":145,"level":31},"b42","📚 Read next",{"id":273,"type":274,"items":275,"ordered":18},"b43","list",[276,277,278],"\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Findexeddb-localstorage-main-thread-blocking\">localStorage Isn&#39;t Free — It&#39;s Blocking Your Main Thread\u003C\u002Fa>","\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweekly-web-workers\">Web Workers in JavaScript: The Complete Guide\u003C\u002Fa>","\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweekly-debounce-and-throttle\">Debounce and Throttle in JavaScript: The Complete Guide\u003C\u002Fa>",{"id":280,"html":281,"type":138},"b44","\u003C!-- related:end -->",{"id":283,"type":284},"b45","divider",{"id":286,"html":287,"type":138},"b46","\u003Cp>🚀 \u003Cstrong>Want more like this?\u003C\u002Fstrong> Every guide, playground, and quiz lives on \u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002F\">bestpractic.org\u003C\u002Fa>\u003C\u002Fstrong> — open it and \u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002F\">sign up free\u003C\u002Fa>\u003C\u002Fstrong> so the next one finds you.\u003C\u002Fp>",{"id":289,"html":290,"type":138},"b47","\u003Cp>\u003Cem>Thanks for reading! Let&#39;s stay connected:\u003C\u002Fem>\u003C\u002Fp>",{"id":292,"type":274,"items":293,"ordered":18},"b48",[294,295,296],"⭐ \u003Cstrong>GitHub\u003C\u002Fstrong> — follow me and star the projects: \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fparsajiravand\">github.com\u002Fparsajiravand\u003C\u002Fa>","💬 \u003Cstrong>Discord\u003C\u002Fstrong> — join the frontend best-practices community: \u003Ca href=\"https:\u002F\u002Fdiscord.gg\u002Fd9KRhuAwQ\">discord.gg\u002Fd9KRhuAwQ\u003C\u002Fa>","📸 \u003Cstrong>Instagram\u003C\u002Fstrong> — frontend best practices, daily: \u003Ca href=\"https:\u002F\u002Fwww.instagram.com\u002Fbestpractice___\u002F\">@bestpractice___\u003C\u002Fa>","The \"export everything\" button had been fine for months. Then someone with eighteen months of notes in the app hit it, and the progress bar started hitching — not failing, just stuttering, every few seconds, like clockwork.\n\nNo errors in the console. No dropped frames in a *normal* sense. Just a build-up feature that got measurably janky exactly in proportion to how much data someone had.\n\n## The buffer builder every binary export reaches for\n\nThe export assembles a single file from chunks — attachments, encoded notes, whatever — arriving over time from IndexedDB, in pieces whose total size you don't know up front. The standard fix for \"I need one contiguous buffer but don't know the final size\" looks like this:\n\n```js\nfunction createGrowableBuffer(initialCapacity = 4096) {\n  let buffer = new ArrayBuffer(initialCapacity);\n  let view = new Uint8Array(buffer);\n  let length = 0;\n\n  function append(bytes) {\n    if (length + bytes.length > buffer.byteLength) {\n      const bigger = new ArrayBuffer(Math.max(buffer.byteLength * 2, length + bytes.length));\n      new Uint8Array(bigger).set(view.subarray(0, length));\n      buffer = bigger;\n      view = new Uint8Array(buffer);\n    }\n    view.set(bytes, length);\n    length += bytes.length;\n  }\n\n  return { append, bytes: () => view.subarray(0, length) };\n}\n```\n\nThis is the pattern you'll find in most hand-rolled binary buffer builders, and it isn't wrong, exactly — doubling capacity is the standard amortized-growth trick, the same one `Array`, `String` concatenation, and `Vec` in other languages all use internally. It's also exactly why this one stutters.\n\n**Before you keep reading: what does every call to `append` actually cost, once the buffer is full?**\n\nA brand-new `ArrayBuffer`, allocated at double the size, and a full copy of *every byte appended so far* into it — then the old buffer becomes garbage. Early on that's nothing: copying 8KB is instant. But capacity doubles each time, so the copies get bigger exactly as the export gets bigger. On a 200MB file built from 4KB chunks, the last couple of growth steps are each copying 50-100MB on the main thread, synchronously, in one `memcpy`-sized function call that blocks everything else — a single-threaded `set()` call doesn't yield partway through. That's the stutter: not a bug, just the doubling trick doing exactly what it's designed to do, at a size where \"exactly what it's designed to do\" is expensive.\n\n## Growing used to mean allocating somewhere else\n\nThe real constraint was never the algorithm — it's that a regular `ArrayBuffer` is a fixed-size, fixed-location block of memory from the moment it's created. \"Growing\" one has only ever meant *creating a different, bigger one* and copying into it, because the original can't get bigger where it already lives.\n\nAs of mid-2024, that's no longer the only option. `ArrayBuffer` can now be created resizable, with a declared ceiling:\n\n```js\nfunction createGrowableBuffer(initialCapacity = 4096, maxCapacity = 512 * 1024 * 1024) {\n  const buffer = new ArrayBuffer(initialCapacity, { maxByteLength: maxCapacity });\n  const view = new Uint8Array(buffer); \u002F\u002F no offset\u002Flength given → tracks the buffer's size automatically\n  let length = 0;\n\n  function append(bytes) {\n    if (length + bytes.length > buffer.byteLength) {\n      buffer.resize(Math.min(maxCapacity, Math.max(buffer.byteLength * 2, length + bytes.length)));\n    }\n    view.set(bytes, length);\n    length += bytes.length;\n  }\n\n  return { append, bytes: () => view.subarray(0, length) };\n}\n```\n\n`buffer.resize()` grows (or shrinks) the *same* allocation — no new `ArrayBuffer`, no copy of the existing bytes, no garbage for the collector to clean up later. The `Uint8Array` built without an explicit length is \"length-tracking\": it automatically reflects however big the underlying buffer currently is, so there's no need to rebuild the view after every resize the way the old version had to.\n\n\u003C!-- playground:start -->\n\n## 🎮 Try it yourself\n\n**[▶️ Open the interactive playground →](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fresizable-arraybuffer-transfer\u002Fplayground)**\n\n_Runs right in your browser — poke at it and watch the concept react live._\n\n\u003C!-- playground:end -->\n\nThe ceiling is real, not a suggestion — ask it to grow past `maxByteLength` and it refuses:\n\n```js\nconst buffer = new ArrayBuffer(1024, { maxByteLength: 4096 });\nbuffer.resize(8192); \u002F\u002F throws — 8192 is past the 4096 you declared up front\n```\n\nYou have to decide the maximum size up front, the same way you'd pass a capacity hint to a `Vec` or a `StringBuilder` in another language. For the export button, that's \"how big could this reasonably ever get\" — a few hundred MB, say — not an unbounded number. That's a feature, not friction: a buffer that could grow to fill all of memory because nobody set a ceiling is its own bug.\n\n## The second bug the fix didn't know it was also fixing\n\nThere was a second, stranger report buried in the same feature: occasionally, a background \"compress before download\" step — handed off to a worker — would silently produce an empty file. Not an error. Just zero bytes, like the buffer had never had anything in it.\n\nThe cause was a few files away from the compression code: a different part of the export flow held a reference to the same raw buffer and had already posted it to *another* worker as a transferable:\n\n```js\nworker.postMessage(rawBuffer, [rawBuffer]);\n\u002F\u002F elsewhere, no error, no warning:\nconsole.log(rawBuffer.byteLength); \u002F\u002F 0\n```\n\n`postMessage`'s transfer list has always worked this way — listing an `ArrayBuffer` there *detaches* it from the sender, handing the actual memory to the receiver with no copy. That's efficient, and it's also completely invisible at the call site that gets bitten by it: nothing about `console.log(rawBuffer.byteLength)` looks wrong, three files away from the `postMessage` call that zeroed it out.\n\n`ArrayBuffer.prototype.transfer()` does the same ownership hand-off, but as a method you call directly, anywhere — not only across a `postMessage` boundary:\n\n```js\nfunction handOff(buffer) {\n  const owned = buffer.transfer(); \u002F\u002F new ArrayBuffer, same bytes where possible, no copy\n  console.log(buffer.detached); \u002F\u002F true — immediately, at the call site that caused it\n  return owned;\n}\n\nconst exported = handOff(rawBuffer);\nworker.postMessage(exported, [exported]);\n```\n\nNothing here is new memory-safety machinery — detaching a buffer and handing its bytes to a new owner is exactly what the transfer list already did. What's new is that it's no longer something that only happens as a side effect of the second argument to `postMessage`. `buffer.transfer()` reads, in the code that calls it, as \"I am done owning this\" — so when something downstream still expects `rawBuffer` to have bytes in it, the bug is one `grep` away from the line that changed it, not a fact about a worker boundary you have to hold in your head.\n\n(If you need the result to definitely *not* be resizable afterward — handing a buffer off to code that assumes a fixed size — `transferToFixedLength()` does the same move and strips the resizability.)\n\n## What the export looks like now\n\nThe buffer builder resizes in place instead of reallocating, so the stutter that scaled with export size is gone — there's no longer a growth step that costs a 100MB copy, because there's no copy at all. And the empty-download bug turned into something `grep`-able: every place a buffer changes hands now says so, in a method name, instead of hiding in a transfer list.\n\nNeither fix needed a library. `resize()`, `transfer()`, and the `maxByteLength` option are Baseline — newly available across Chrome, Firefox, and Safari since 2024 (`transfer()` reached Baseline first, in March 2024; resizable buffers followed that July, once Firefox shipped `resize()` too) — so if your target browsers are current, this is just how `ArrayBuffer` works now. If you still support something older, feature-detect before you lean on it:\n\n```js\nconst hasResizableBuffers = typeof ArrayBuffer.prototype.resize === \"function\";\n```\n\nIf you've got a doubling-buffer builder living in a binary parser or an export feature somewhere, it's probably not causing a problem yet — it's just waiting for someone with enough data to feel the copy. Have you been bitten by a buffer that went quietly empty after a `postMessage` call you weren't looking at?\n\n\u003C!-- quiz:start -->\n\n## 🧠 Test yourself\n\nThink it clicked? **[Take the 6-question quiz →](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fresizable-arraybuffer-transfer\u002Fquiz)**\n\n_Instant feedback, a hint on every question, and an explanation for each answer — right or wrong._\n\n\u003C!-- quiz:end -->\n\n\u003C!-- related:start -->\n\n## 📚 Read next\n\n- [localStorage Isn't Free — It's Blocking Your Main Thread](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Findexeddb-localstorage-main-thread-blocking)\n- [Web Workers in JavaScript: The Complete Guide](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweekly-web-workers)\n- [Debounce and Throttle in JavaScript: The Complete Guide](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweekly-debounce-and-throttle)\n\n\u003C!-- related:end -->\n\n---\n\n🚀 **Want more like this?** Every guide, playground, and quiz lives on **[bestpractic.org](https:\u002F\u002Fbestpractic.org\u002F)** — open it and **[sign up free](https:\u002F\u002Fbestpractic.org\u002F)** so the next one finds you.\n\n*Thanks for reading! Let's stay connected:*\n\n- ⭐ **GitHub** — follow me and star the projects: [github.com\u002Fparsajiravand](https:\u002F\u002Fgithub.com\u002Fparsajiravand)\n- 💬 **Discord** — join the frontend best-practices community: [discord.gg\u002Fd9KRhuAwQ](https:\u002F\u002Fdiscord.gg\u002Fd9KRhuAwQ)\n- 📸 **Instagram** — frontend best practices, daily: [@bestpractice___](https:\u002F\u002Fwww.instagram.com\u002Fbestpractice___\u002F)",{"title":111,"canonical":299,"description":300},"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fresizable-arraybuffer-transfer","Every \"growable buffer\" helper allocates bigger, copies everything in, and throws the old buffer away — on a 200MB export that copy is a visible stutter. Resizable ArrayBuffer grow","01a21cc5-6a9e-740d-b36d-d2063dad9ab1",{"id":303,"locked":18},"01a21cc5-6abd-71ab-bf02-09af2257f87b",[305],{"id":45,"slug":46,"title":48,"_count":306},{"questions":51},[308],{"locale":13,"slug":46},{"id":45,"slug":46,"title":48,"_count":310,"questionCount":51},{"questions":51},[]]