diff --git a/lib/codemirror.js b/lib/codemirror.js
index 2fe344e0717f4c029247a2dacd5156516fd7615d..37a0fd92dde2f67d41c0a0f8043a956234832eab 100644
--- a/lib/codemirror.js
+++ b/lib/codemirror.js
@@ -7315,21 +7315,17 @@
         var child = this.children[i], sz = child.chunkSize();
         if (at <= sz) {
           child.insertInner(at, lines, height);
-          var childLines = child.lines;
-          var childLinesLen = childLines && childLines.length;
-          if (childLinesLen > 50) {
-            // To avoid memory thrashing when childLines is huge (e.g. first view of a large file), it's never spliced.
+          if (child.lines && child.lines.length > 50) {
+            // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
             // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
-            var numNewLeafs = Math.ceil((childLinesLen - 50) / 25);
-            var newChildLinesLen = childLinesLen - numNewLeafs * 25;
-            child.lines = childLines.slice(0, newChildLinesLen);
-            for (var j = 0; j < numNewLeafs; j++) {
-              var leafStart = newChildLinesLen + j * 25;
-              var leaf = new LeafChunk(childLines.slice(leafStart, leafStart + 25));
+            var remaining = child.lines.length % 25 + 25
+            for (var pos = remaining; pos < child.lines.length;) {
+              var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
               child.height -= leaf.height;
-              this.children.push(leaf);
+              this.children.splice(++i, 0, leaf);
               leaf.parent = this;
             }
+            child.lines = child.lines.slice(0, remaining);
             this.maybeSpill();
           }
           break;