DEV Community


Discussion on: Leetcode MinStack Design Problem: JavaScript Low Level Solution

definite2 profile image
Defne Eroğlu Author • Edited

Thank you for your comments Alfredo. My point in this blog to share this particular solution I've submitted to leetcode. And I know, in the description of the problem, there is no rule that we cannot use push(), pop() or length functions and props ; but this was my solution. And I just wanted to share....
But your comment was very beneficial for me! Because I've gone more detail about these native functions, at least first just by google'ing the topic (as searching with the question that push() vs index assignment). Than I've found somethings I would like to share with you too.
The first search result I've found was from stackoverflow:
This post implies that push() is slower than array assignment. And I've found some similar discussions from old times they also say that push() is slower than array assignment. But they are very old post. I know node.js is much more better now and also the javascript engines of the browsers are increased in their performance. Than
I've made a test and my test environment is: Lenova, i7, node.js v12.18.3
Here is the test code:

var i = 0
var ar = []

i = 0
console.time("With index assignment")
  ar[i] = i
console.timeEnd("With index assignment")

i = 0
ar = []
console.time("With push()")
console.timeEnd("With push()")
Enter fullscreen mode Exit fullscreen mode

And the result! push() is faster than index assignment! According to my tests you are right at the saying push(), pop() is faster than but; in the 2015 you were wrong I suppose... Anyways. As I've told at the beginning, I don't say this is the best and optimal solution, btw it was better the 75% of other commiters' submissions, my aim was to write these functions without Javascript's native related functions...And thank you again of course for your comment.

rahxuls profile image

Thank you for this. It seems a new post in Comments.