Confirm the Ending right approach

Tell us what’s happening:
My code is working, I am just curious if its more efficent to use substring (my approach) or slice (solution). Would appreciate if some1 could explain why.

Thanks alot!

Solution provided from FCC:

  return str.slice(str.length - target.length) === target;

Your code so far


function confirmEnding(str, target) {
  // "Never give up and good luck will find you."
  // -- Falcor
  return str.substring(str.length-target.length, str.length) == target ? true : false;
}

console.log(confirmEnding("He has to give me a new name", "name"));


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/confirm-the-ending

Substring version is slightly faster, but not in any meaningful way:

sliceVersion x 611,120,795 ops/sec ±2.12% (79 runs sampled)
substringVersion x 624,514,736 ops/sec ±2.11% (83 runs sampled)
Fastest is substringVersion

Benchmark code:

var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
var str = 'He has to give me a new name';
var target = 'name';


function sliceVersion(str, target) {
  return str.slice(str.length - target.length) === target;
}

function substringVersion(str, target) {
  return str.substring(str.length-target.length, str.length) == target ? true : false;
}


// add tests
suite.add('sliceVersion', function() {
  sliceVersion(str, target)
})
.add('substringVersion', function() {
  substringVersion(str, target)
})
// add listeners
.on('cycle', function(event) {
    console.log(String(event.target));
})
.on('complete', function() {
    console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });