TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Algorithmic Complexity of Left-Pad (2016)

68 pointsby pcr910303almost 4 years ago

7 comments

kccqzyalmost 4 years ago
The fact that the Safari result appears to have two linear fits doesn&#x27;t surprise me at all. Apple has a history of implementing multiple concrete classes for different sizes for the same abstract class. It has been known that NSArray and CFArray will switch the underlying data structure once it grows past a certain size: <a href="https:&#x2F;&#x2F;ridiculousfish.com&#x2F;blog&#x2F;posts&#x2F;array.html" rel="nofollow">https:&#x2F;&#x2F;ridiculousfish.com&#x2F;blog&#x2F;posts&#x2F;array.html</a> Now I&#x27;m not saying this NSArray trick was what happened here: it clearly is not because otherwise we&#x27;d see a quadratic curve followed by a linear curve. I&#x27;m just saying the data structure seems to have changed at a certain size cutoff.
throwanemalmost 4 years ago
An optimized implementation (as &quot;padStart&quot;) is in the standard library now: <a href="https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Web&#x2F;JavaScript&#x2F;Reference&#x2F;Global_Objects&#x2F;String&#x2F;padStart" rel="nofollow">https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Web&#x2F;JavaScript&#x2F;Refe...</a>
评论 #28020855 未加载
brundolfalmost 4 years ago
&gt; But the principle remains, that it was actually completely impossible for us to analyze left-pad’s performance without a deep understanding of the specific underlying Javascript VM we cared about (or, in my case, resorting to brute experiment!).<p>And this is why we benchmark before optimizing
jonathrgalmost 4 years ago
It had been optimized (and deprecated) since then. See <a href="https:&#x2F;&#x2F;github.com&#x2F;left-pad&#x2F;left-pad&#x2F;blob&#x2F;master&#x2F;index.js" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;left-pad&#x2F;left-pad&#x2F;blob&#x2F;master&#x2F;index.js</a>
评论 #28023915 未加载
评论 #28020795 未加载
iamcreasyalmost 4 years ago
I am wondering if the graph that shows Safari performance is actually quadratic. I am referring to the the 2nd linear segment.<p>On that graph, 400,000 length required 2500 in time. If it&#x27;s quadratic, 800,000 would require 10,000 in time. If you imagine the plot goes all the way to 800,000 - it&#x27;s not hard to see that the line&#x2F;curve hitting at 10,000.<p>Thoughts?
评论 #28022741 未加载
8bitsrulealmost 4 years ago
After pre-creating a pad-string constant of sufficient length, no loop is needed. For each target$, calculate how long the needed pad is, grab that many characters, and prepend.
kevillealmost 4 years ago
(Circa 2016)
评论 #28020263 未加载