Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Faster Cloning #1

Open
splitice opened this issue Oct 21, 2020 · 0 comments
Open

Faster Cloning #1

splitice opened this issue Oct 21, 2020 · 0 comments

Comments

@splitice
Copy link

function fn(){
	
}
const CloneSymbol = Symbol()
function cloner(obj){
	obj[CloneSymbol] = ()=>{return {"_id":"ididid", v: 1, a: "abc"}}
	return obj
}
const obj = cloner({"_id":"ididid", v: 1, a: "abc"})
for(let i=0;i<1000;i++){
	fn(obj[CloneSymbol]())
}

performs at-least 10x faster than

function fn(){
	
}

function deepCopy (obj) {
  let res;

  if ( typeof obj === 'boolean' ||
       typeof obj === 'number' ||
       typeof obj === 'string' ||
       obj === null ||
       (obj instanceof Date) ) {
    return obj;
  }

  
  if (Array.isArray(obj)) {
    res = new Array(obj.length);
    for(let i = obj.length; i--;){
      res[i] = deepCopy(obj[i]);
    }
    return res;
  }


  if (typeof obj !== 'object') return undefined;   // For now everything else is undefined. We should probably throw an error instead
  
  res = {};
  for(const k in obj){
    res[k] = deepCopy(obj[k]);
  }
  return res;
}

const obj = {"_id":"ididid", v: 1, a: "abc"}
for(let i=0;i<1000;i++){
	fn(deepCopy(obj))
}

Would use 2x memory, and only make sense for read frequently databases that don't use findUnsafe or use the return value from update

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant