Make code easier to read: Imperative vs Functional

JavaScript performance comparison

Test case created by cristi-salcescu

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  //Functional
  function isPriorityTask(task){
     return task.type === "RE" && !task.completed;
  }
  
  function toTaskView(task) {
     return { ...task, userName: task.user.name };
  }
  
  //Generate tasks
  function createALotOfTasks(){
  	const arr = [];
    
    for(i=0; i < 100000; i++){
      let isReview = Math.round(Math.random());
    	arr.push({ 
        id : i,
        type : (isReview) ? "RE" : "NC",
        desc : "task" + i,
        user : { id: i, name: "user" + i},
        completed : false
   	 	});
    }
    return arr;
  }
  
  const tasks = createALotOfTasks();

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Imperative: for-loop
let filteredTasks = [];
for(let i=0; i<tasks.length; i++){
    let task = tasks[i];
    if (task.type === "RE" && !task.completed) {
       filteredTasks.push({ ...task, userName: task.user.name });
    }
}
pending…
Functional: filter, map
let filteredTasks = tasks.filter(isPriorityTask).map(toTaskView);
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 Comments