Skip to content

Instantly share code, notes, and snippets.

@dmarcelino
Created June 3, 2015 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmarcelino/5dc29b529183d9e38a54 to your computer and use it in GitHub Desktop.
Save dmarcelino/5dc29b529183d9e38a54 to your computer and use it in GitHub Desktop.
Comparing strategies to match RecordID
var assert = require('assert');
var RecordId = require('oriento').RID;
var _ = require('lodash');
var N = 4000;
function matchRecordIdOriginal(id) {
if (id === null || id == undefined) return false;
var test = _.cloneDeep(id);
if(typeof test.toString !== 'undefined')
test = id.toString();
return test.match(/^\#\-?\d+\:\d+$/) ? true : false;
};
function matchRecordIdNew(id) {
if (!id) return false;
if(id instanceof RecordId) { return true; }
var test = id.toString();
return test.match(/^\#\-?\d+\:\d+$/) ? true : false;
};
function test(fn){
var fixturesTrue = [
new RecordId('#10:1'),
new RecordId('#0:0'),
new RecordId('#-2:1'),
'#5:5',
'#5:0',
'#-2:0',
'#-2:1'
];
var fixturesFalse = [
null,
undefined,
4,
'5',
'5:5',
'-2:1',
'#5',
'#5:5:5',
'#2:-1',
'#:1'
];
fixturesTrue.forEach(function(rid){
assert.equal(fn(rid), true, 'test failed for: ' + rid);
});
fixturesFalse.forEach(function(rid){
assert.equal(fn(rid), false, 'test failed for: ' + rid);
});
}
console.time('matchRecordIdOriginal');
for(var i=0; i<N; i++){
test(matchRecordIdOriginal);
}
console.timeEnd('matchRecordIdOriginal');
console.time('matchRecordIdNew');
for(var i=0; i<N; i++){
test(matchRecordIdNew);
}
console.timeEnd('matchRecordIdNew');
console.time('matchRecordIdNew');
for(var i=0; i<N; i++){
test(matchRecordIdNew);
}
console.timeEnd('matchRecordIdNew');
console.time('matchRecordIdOriginal');
for(var i=0; i<N; i++){
test(matchRecordIdOriginal);
}
console.timeEnd('matchRecordIdOriginal');
/**
* matchRecordIdNew is 2.5x faster
* matchRecordIdOriginal: 54ms
* matchRecordIdNew: 17ms
* matchRecordIdNew: 17ms
* matchRecordIdOriginal: 44ms
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment