opcode: experiment with using cached opcodes.

This commit is contained in:
Christopher Jeffrey 2017-08-19 23:14:30 -07:00
parent 5047028511
commit 2647d011dc
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD

View File

@ -15,6 +15,8 @@ const BufferReader = require('../utils/reader');
const StaticWriter = require('../utils/staticwriter');
const opcodes = common.opcodes;
const cache = [];
/**
* A simple struct which contains
* an opcode and pushdata buffer.
@ -271,6 +273,16 @@ Opcode.prototype.fromRaw = function fromRaw(data) {
*/
Opcode.fromReader = function fromReader(br) {
if (br.offset < br.data.length) {
const op = br.data[br.offset];
const cached = cache[op];
if (cached) {
br.offset++;
return cached;
}
}
return new Opcode(0, null).fromReader(br);
};
@ -281,6 +293,14 @@ Opcode.fromReader = function fromReader(br) {
*/
Opcode.fromRaw = function fromRaw(data) {
if (data.length > 0) {
const op = data[0];
const cached = cache[op];
if (cached)
return cached;
}
return new Opcode(0, null).fromRaw(data);
};
@ -291,6 +311,11 @@ Opcode.fromRaw = function fromRaw(data) {
*/
Opcode.fromOp = function fromOp(op) {
const cached = cache[op];
if (cached)
return cached;
return new Opcode(op, null);
};
@ -454,6 +479,23 @@ Opcode.isOpcode = function isOpcode(obj) {
&& (Buffer.isBuffer(obj.data) || obj.data === null);
};
/*
* Fill Cache
*/
for (let value = 0x00; value <= 0xff; value++) {
if (value >= 0x01 && value <= 0x4e) {
cache.push(null);
continue;
}
const op = new Opcode(value);
Object.freeze(op);
cache.push(op);
}
/*
* Expose
*/