-
Notifications
You must be signed in to change notification settings - Fork 140
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
optimized memory usage by maintaining encoded GIF data in a Uint8Arra…
…y instead of a classical untyped Array Since a Uint8Array uses only 1 byte per element and every number is likely a 64-bit floating point number, Uint8Array should be a much more compact way to store the data. This change was tested by running encoding the same frames of a long gif animation that previously crashed the browser every time on the same laptop, same browser, same version of Windows...
- Loading branch information
Showing
2 changed files
with
56 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
/** | ||
* This class represents an array of bytes in a compact, memory-efficient format. | ||
* This was written to be used by GIFEncoder so it could encode larger GIF files than possible with a non-typed Array of number. | ||
* @author Josh Greig | ||
*/ | ||
function DynamicByteArray() { | ||
var arr = new Uint8Array(1000); | ||
var len = 0; | ||
|
||
function expandCapacity() { | ||
var newCapacity = arr.length * 2; | ||
// If the capacity is huge, the risk of running out of memory is higher | ||
// so we want to expand in 50% intervals instead of 100% intervals. | ||
if (newCapacity > 50000000) { | ||
newCapacity = arr.length * 1.5; | ||
} | ||
var newArr = new Uint8Array(newCapacity); | ||
for (let i = 0; i < arr.length; i++) { | ||
newArr[i] = arr[i]; | ||
} | ||
arr = newArr; | ||
} | ||
|
||
DynamicByteArray.prototype.get = function(index) { | ||
return arr[index]; | ||
}; | ||
|
||
DynamicByteArray.prototype.getLength = function() { | ||
return len; | ||
} | ||
|
||
DynamicByteArray.prototype.toCompactUint8Array = function() { | ||
if (arr.length !== len) { | ||
const result = new Uint8Array(len); | ||
for (let i = 0; i < len; i++) { | ||
result[i] = arr[i]; | ||
} | ||
arr = result; | ||
} | ||
return arr; | ||
}; | ||
|
||
DynamicByteArray.prototype.writeByte = function(val) { | ||
if (len >= arr.length) { | ||
expandCapacity(); | ||
} | ||
arr[len++] = val; | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters