TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Ask HN: What's the most elegant piece of code you've seen?

139 点作者 mc42超过 9 年前
Lots of people have spent years writing programs spanning platforms, servers, services, and languages. However, efficient and elegant code is far and few between.<p>What code has stood out to you for being elegant and efficient? Why or why not?

38 条评论

nostrademons超过 9 年前
Jeff Dean&#x27;s original implementation of MapReduce.<p>It was, IIRC, only 3 C++ classes and just a few hundred lines of code. It outsourced much of the distribution, task running, and disk-access tasks to other Google infrastructure, and only focused on running the computation, collecting results for each key, and distributing to the reducers.<p>The current (as of ~2012, so not that current anymore) version of MapReduce is much faster and more reliable, but there&#x27;s a certain elegance to starting a trillion-dollar industry with a few hundred lines of code.<p>There was another doozy, also by Jeff Dean, in the current (again, as of 2012) MapReduce code. It was an external sorting algorithm, and like most external sorts, it worked by writing a bunch of whole-machine-RAM sized temporary files and then performing an N-way merge. But how did it sort the machine&#x27;s RAM? Using the STL qsort() function, of course! But how do you sort ~64GB of data efficiently using a standard-library function? He&#x27;d written a custom comparator that compared whole records at a time, using IIRC compiler intrinsics that compiled down into SIMD instructions and did some sort of Duff&#x27;s-Device like unrolling to account for varying key lengths. It was a very clever mix of stock standard library functions with highly-optimized, specialized code.
评论 #11005378 未加载
评论 #11005994 未加载
评论 #11005784 未加载
Chris_Newton超过 9 年前
On a larger scale than most suggestions so far, I’ve always been impressed with SQLite. The developers have managed to create a useful-in-the-real-world tool, small and efficient enough for even quite demanding applications like embedded systems work.<p>The original source code was solid and well documented in the parts I’ve seen, but the remarkable thing to me is the way they distribute it: it comes as a single ANSI C file and a single matching header, which they refer to as the “amalgamation”. It therefore works just about anywhere, has no packaging or dependency hell issues, can be be incorporated into any build process in moments, and can be statically linked and fully optimised.
评论 #11005896 未加载
bosky101超过 9 年前
Joe Armstrong - the creator of erlang would turn his cluster of 1000&#x27;s of machines to change behaviour. The code is really 5 lines.<p><pre><code> My favorite Erlang program 21 Nov 2013 The other day I got a mail from Dean Galvin from Rowan University. Dean was doing an Erlang project so he asked “What example program would best exemplify Erlang”. ... The Universal Server Normally servers do something. An HTTP server responds to HTTP requests and FTP server responds to FTP request and so on. But what about a Universal Server? surely we can generalize the idea of a server and make a universal server that which we can later tell to become a specific sever. Here’s my universal server: universal_server() -&gt; receive {become, F} -&gt; F() end. ...then I set up a gossip algorithm to flood the network with become messages. Then I had an empty network that in a few seconds would become anything I wanted it to do. </code></pre> a process in erlang, is nothing but a tail-recursive function. the moment it stops being so - it dies. so here it morphes into F; which can be passed in.<p>more at <a href="http:&#x2F;&#x2F;joearms.github.io&#x2F;2013&#x2F;11&#x2F;21&#x2F;My-favorite-erlang-program.html" rel="nofollow">http:&#x2F;&#x2F;joearms.github.io&#x2F;2013&#x2F;11&#x2F;21&#x2F;My-favorite-erlang-progr...</a>
wasd超过 9 年前
I love the story of the fast inverse square root. A bizzare piece of code from quake 3 shows up on usenet with a magic constant that calculates the inverse square root faster than table lookups and approximately four times faster than regular floating point division. Inverse square roots are used to compute angles of incidence and reflection for lighting and shading in computer graphics. Author unknown but was once thought as of Carmack.<p><a href="https:&#x2F;&#x2F;en.m.wikipedia.org&#x2F;wiki&#x2F;Fast_inverse_square_root" rel="nofollow">https:&#x2F;&#x2F;en.m.wikipedia.org&#x2F;wiki&#x2F;Fast_inverse_square_root</a>
评论 #11005602 未加载
dividuum超过 9 年前
That has to be LuaJIT. The amount of knowledge hidden in that code base is mind blowing. It contains a state of the art tracing JIT compiler, optimized for at least 5 different platforms, a custom assembler (dynasm) which is used for implementing hand optimized code for the interpreter in 6 different architectures. Additionally it has one of the best FFI implementations I&#x27;ve ever seen: Just parse a C-header file at runtime and you can call into C code with zero overhead. All of that written by a single person (Mike Pall). If you haven&#x27;t had a look, you should: <a href="https:&#x2F;&#x2F;github.com&#x2F;LuaJIT&#x2F;LuaJIT&#x2F;tree&#x2F;v2.1" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;LuaJIT&#x2F;LuaJIT&#x2F;tree&#x2F;v2.1</a>
评论 #11007683 未加载
danielvf超过 9 年前
The Redis source code is hand down the best C I&#x27;ve ever seen. And it&#x27;s not just the code that&#x27;s beautiful - the tests are too.<p><a href="https:&#x2F;&#x2F;github.com&#x2F;antirez&#x2F;redis&#x2F;blob&#x2F;unstable&#x2F;src&#x2F;dict.c" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;antirez&#x2F;redis&#x2F;blob&#x2F;unstable&#x2F;src&#x2F;dict.c</a>
tebeka超过 9 年前
Peter Norvig&#x27;s Spell Checker <a href="http:&#x2F;&#x2F;norvig.com&#x2F;spell-correct.html" rel="nofollow">http:&#x2F;&#x2F;norvig.com&#x2F;spell-correct.html</a><p>A lot of other code he writes as well.
评论 #11005331 未加载
评论 #11005995 未加载
评论 #11005369 未加载
d13超过 9 年前
Commodore 64&#x27;s Basic random maze generator:<p>10 PRINT CHR$(205.5+RND(1)); : GOTO 10<p><a href="https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=m9joBLOZVEo" rel="nofollow">https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=m9joBLOZVEo</a>
评论 #11005495 未加载
评论 #11005330 未加载
评论 #11008599 未加载
lokedhs超过 9 年前
The Solaris kernel source. I got a deep appreciation for the elegance of it when I was working for Sun a long time ago. I can enjoy analysing that code base, which is opposite to the feeling I get when looking at the Linux code.<p>It&#x27;s not overly clever, but it&#x27;s incredibly clear and easy to understand.
评论 #11005750 未加载
评论 #11006271 未加载
jamessantiago超过 9 年前
Doom 3 was touted[1] as having some &quot;exceptional beauty.&quot; Naming, spacing of properties, consistency, and how multiple parameterized calls were formatted are quite nice. You can see an example on github[2], but for some reason the spacing is a bit off in the web view. I&#x27;d recommend cloning a local copy and taking a look.<p>[1] <a href="http:&#x2F;&#x2F;kotaku.com&#x2F;5975610&#x2F;the-exceptional-beauty-of-doom-3s-source-code" rel="nofollow">http:&#x2F;&#x2F;kotaku.com&#x2F;5975610&#x2F;the-exceptional-beauty-of-doom-3s-...</a><p>[2] <a href="https:&#x2F;&#x2F;github.com&#x2F;id-Software&#x2F;DOOM-3&#x2F;blob&#x2F;master&#x2F;neo&#x2F;game&#x2F;ai&#x2F;AI.cpp" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;id-Software&#x2F;DOOM-3&#x2F;blob&#x2F;master&#x2F;neo&#x2F;game&#x2F;a...</a>
评论 #11005628 未加载
jessedhillon超过 9 年前
Fast inverse square root[0] is something that I encountered in the mid-2000s in the Q3A source code. It took me a really long time to understand it, and I eventually had to show it to some professors before I really understood what was going on and why this worked.<p>That&#x27;s really an example of how arbitrary human thought processes are. When you release the constraint that your code has to have some human-comprehensible analog, you might arrive at interesting results.<p>[0] <a href="https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Fast_inverse_square_root" rel="nofollow">https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Fast_inverse_square_root</a>
评论 #11005522 未加载
afrancis超过 9 年前
It has been a while since I looked at it, but I was impressed by Russ Cox&#x27;s implementation of channels in the LibThread library of Plan 9. All channel operations including blocking on several channels and selecting one that is ready, are described by Alt structures, which under the hood implement a simple but elegant algorithm that appears in Rob Pike&#x27;s &quot;The Implementation of Newsqueak.&quot; I feel you want to understand roughly how Go channels works, read that paper and look at LibThread&#x27;s channel implementation.<p>A second choice would not be so much code, but an algorithm: Thompson constructions for regular expressions.
评论 #11030724 未加载
Radim超过 9 年前
For me, the memorable pieces of code are those that made me &quot;want to become a programmer&quot;, to choose the path I chose, way back in the day.<p>Unsurprisingly, these were games:<p>1) A C64 &quot;SnakeByte-like&quot; game, whose exact name I forgot. It was written entirely in BASIC 2.0 (so you could list and read the source code), and with me having no C64 manual, and no English, it was a true revelation. So much fun and beauty emerging from such a concise, approachable program!<p>2) An ancient five-in-a-row implementation, I think in BASIC again or maybe Pascal. I remember the shock after seeing how simple the code was, compared to its (surprisingly good) playing strength and speed. My github user name, &quot;piskvorky&quot;, is an echo of this old experience :-)<p>The underlying appeal seems to be a combination of simple, elegant rules giving rise to complex and fun behaviour. That, to me, is elegance.
FrankyHollywood超过 9 年前
This question was asked to some top programmers and computer scientists. The answers are collected in this book:<p><a href="http:&#x2F;&#x2F;www.worldofbooks.com&#x2F;catalog&#x2F;product&#x2F;view&#x2F;id&#x2F;2366045&#x2F;s&#x2F;beautiful-code-by-greg-wilson&#x2F;category&#x2F;126&#x2F;" rel="nofollow">http:&#x2F;&#x2F;www.worldofbooks.com&#x2F;catalog&#x2F;product&#x2F;view&#x2F;id&#x2F;2366045&#x2F;...</a>
SixSigma超过 9 年前
The Plan9 Source code<p><a href="https:&#x2F;&#x2F;github.com&#x2F;0intro&#x2F;plan9" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;0intro&#x2F;plan9</a><p>&gt; A Professor of Computer Science gave a paper on how he uses Linux to teach his undergraduates about operating systems. Someone in the audience asked &#x27;why use Linux rather than Plan 9?&#x27; and the professor answered: Plan 9 looks like it was written by experts; Linux looks like something my students could aspire to write.<p>But see also the HN thread :<p>Code which every programmer must read before dying<p><a href="https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=2466129" rel="nofollow">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=2466129</a>
eps超过 9 年前
I worked for a networking software developer at some point in the past and they were considering licensing a VPN stack from the SSH company [1]. That thing was in C and the sample code included was stunningly beautiful as was the documentation - well modularized, consistent, good naming notation, but above all it was concise. I think I still have a CD with the SDK demo, I can pull up some code from there if anyone&#x27;s interested.<p>[1] <a href="https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;SSH_Communications_Security" rel="nofollow">https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;SSH_Communications_Security</a>
rajathagasthya超过 9 年前
I was reading some of the Python standard library code and one piece stood out for me in the heapq.py module.<p>Merge sorted iterables using min heap:<p><pre><code> def merge(*iterables): &#x27;&#x27;&#x27;Merge multiple sorted inputs into a single sorted output. &gt;&gt;&gt; list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25])) [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25] &#x27;&#x27;&#x27; _heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration _len = len h = [] h_append = h.append for itnum, it in enumerate(map(iter, iterables)): try: next = it.next h_append([next(), itnum, next]) except _StopIteration: pass heapify(h) while _len(h) &gt; 1: try: while 1: v, itnum, next = s = h[0] yield v s[0] = next() # raises StopIteration when exhausted _heapreplace(h, s) # restore heap condition except _StopIteration: _heappop(h) # remove empty iterator if h: # fast case when only a single iterator remains v, itnum, next = h[0] yield v for v in next.__self__: yield v </code></pre> If I&#x27;m not wrong, this is written by Raymond Hettinger and it&#x27;s always a pleasure to read&#x2F;use his code.
评论 #11007592 未加载
sssilver超过 9 年前
Naive factorial implementation in Haskell<p>factorial 0 = 1<p>factorial n = n * factorial (n - 1)
评论 #11078722 未加载
davidjnelson超过 9 年前
I really like the code for redux. It&#x27;s only a few hundred lines of code, but has spawned an ecosystem of plugins and has over 13,000 github stars already.<p><a href="https:&#x2F;&#x2F;github.com&#x2F;rackt&#x2F;redux&#x2F;tree&#x2F;master&#x2F;src" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;rackt&#x2F;redux&#x2F;tree&#x2F;master&#x2F;src</a>
评论 #11008733 未加载
visof超过 9 年前
quicksort [] = []<p>quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)<p><pre><code> where lesser = filter (&lt; p) xs greater = filter (&gt;= p) xs</code></pre>
评论 #11006504 未加载
semberal超过 9 年前
Definitely the implementation of a (simplified) Scheme interpreter in Scheme we were doing years ago in a functional programming course on university. It made me fall in love with functional programming.
pillmuncher超过 9 年前
From Sterling and Shapiro&#x27;s &quot;The Art of Prolog&quot; a procedure to concat two difference lists in O(1) time (from memory):<p><pre><code> append_dl(A - B, B - C, A - C).</code></pre>
projectileboy超过 9 年前
I learned a lot reading Paul Graham&#x27;s source code for Arc. And John Carmack&#x27;s (and others) code for Quake is also very educational.
EliRivers超过 9 年前
C string copy.<p><pre><code> while (*p++ = *q++);</code></pre>
评论 #11008088 未加载
lutusp超过 9 年前
&gt; What&#x27;s the most elegant piece of code you&#x27;ve seen?<p>Well, not the most elegant, but a very elegant piece of code, solves the Towers of Hanoi puzzle in a few ingenious lines (Python as shown):<p><pre><code> def printMove(disk,src,dest): print(&quot;Move disk %d from %s to %s&quot; % (disk,src,dest)) def moveDisk(disk,src, dest, using): if disk &gt;= 1: moveDisk(disk-1,src,using,dest) printMove(disk,src,dest) moveDisk(disk-1,using,dest,src) count = 3 moveDisk(count,&#x27;A&#x27;,&#x27;B&#x27;,&#x27;C&#x27;) </code></pre> Result:<p><pre><code> Move disk 1 from A to B Move disk 2 from A to C Move disk 1 from B to C Move disk 3 from A to B Move disk 1 from C to A Move disk 2 from C to B Move disk 1 from A to B</code></pre>
bitwize超过 9 年前
Duff&#x27;s Device.<p>Much of the NetBSD code base.<p>Pick a hack by Oleg Kiselyov.<p>The Commodore KERNAL.
mitchtbaum超过 9 年前
Turbo&#x27;s code seems very beautiful to me. Before finding this, I saw web servers as either a big-black-box, coded in a hard to grok systems language (Apache and Nginx), or as a testing tool written in a slow, but readable scripting language (Python or PHP). Now, I can dive into a fast, robust, and easy to read web server (and client) to see nearly every bit of functionality. Lua continues to impress and strike me as a great language for web development.<p><a href="https:&#x2F;&#x2F;github.com&#x2F;kernelsauce&#x2F;turbo" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;kernelsauce&#x2F;turbo</a>
jacquesm超过 9 年前
Hands down Peter Norvig&#x27;s hashlife and sudoku solver.
vayeate超过 9 年前
I have limited exposure being a junior web dev, but I find Laravel to be very well structured and what some might describe as Elegant. Jeffrey Way discussed his opinions on it that I agree with last year at a Laracon: <a href="https:&#x2F;&#x2F;youtu.be&#x2F;mDotS5BDqRM?t=1539" rel="nofollow">https:&#x2F;&#x2F;youtu.be&#x2F;mDotS5BDqRM?t=1539</a>
评论 #11009205 未加载
thiht超过 9 年前
Although I&#x27;m not much of a C guy, I really enjoy reading ANSI C. I like the Lua source code[1] for instance.<p>[1]: <a href="https:&#x2F;&#x2F;github.com&#x2F;lua&#x2F;lua&#x2F;tree&#x2F;master&#x2F;src" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;lua&#x2F;lua&#x2F;tree&#x2F;master&#x2F;src</a>
networked超过 9 年前
In the sense that perfection is achieved when there is nothing left to take away, GO.COM as described in <a href="http:&#x2F;&#x2F;peetm.com&#x2F;blog&#x2F;?p=55" rel="nofollow">http:&#x2F;&#x2F;peetm.com&#x2F;blog&#x2F;?p=55</a>. It doubles as a winning entry in 1994&#x27;s IOCCC.
kpil超过 9 年前
Although not &#x27;real&#x27; code, almost anything from The Wizard Book is either nice, elegant or sometimes a minor epiphany for a C-damaged mind...<p>Probably not that efficient in terms of raw CPU grunt though...
nine_k超过 9 年前
Lisp interpreter loop.
contingencies超过 9 年前
<i>exit()</i>
camperman超过 9 年前
A quiz question from the old Imphobia demo diskmag: a single instruction to extend a byte value in al across a full 32-bit word. Impossible right? Nope:<p><pre><code> imul 0x01010101</code></pre>
throwaway420超过 9 年前
Some people might hate this answer, but sometimes the most elegant piece of code doesn&#x27;t actually exist.<p>Code is a tool that is used to solve problems. Sometimes the most elegant solution to a problem doesn&#x27;t involve writing code, but involves examining a business process and changing the work flow a bit to avoid needing to code something...or rewording an item in the user interface so that certain code isn&#x27;t anymore needed.<p>Sometimes rather than being a drone and just churning out whatever code you&#x27;re told, the bravest and most elegant solution to a problem is figuring out a way to avoid it altogether.<p>This is the hardworking lazy programmer&#x27;s most elegant code.
irascible超过 9 年前
duffs device.
jcoffland超过 9 年前
Perl 6......JK of course.
评论 #11015249 未加载
评论 #11008211 未加载