Hacker Newsnew | past | comments | ask | show | jobs | submit | more phpnode's commentslogin

regarding your edit, you're exactly right, of course a for loop will be faster. Sometimes you really do need a function call though, in which case fast forEach and map implementations become more useful.

The next step for fast.js are some sweet.js macros which will make writing for loops a bit nicer, because it's pretty painful to write this every time you want to iterate over an object:

    var keys = Object.keys(obj),
        length = keys.length,
        key, i;
    for (i = 0; i < length; i++) {
      key = keys[i];
      // ...
    }
I'd rather write:

   every key of obj {
     // ...
   }
and have that expanded at compile time.

Additionally there are some cases where you must use inline for loops (such as when slicing arguments objects, see https://github.com/petkaantonov/bluebird/wiki/Optimization-k...) and a function call is not possible. These can also be addressed with sweet.js macros.


To be fair, it's not obvious if you're not a JS expert: coming from some other language, you could naively assume that function call gets inlined, with no overhead.


A few months ago, I tried some image processing with JS and the canvas object (big Arrays).

They have a structure like image[pixel].color

What I found was, always traversing the object structure was much slower than putting every pixel color as an argument in a function, that gets called every iteration.

So I had the impression, reasonable simple function, like a greyscale filter, get inlined by engines like V8.


You probably would have been better off with typed arrays and fragment shaders, if you were going for performance.


Aren't the arrays produced by a canvas object typed?


Yep, but they only become performant when you treat them as such instead of doing naive e.g. multiplication. See: https://hacks.mozilla.org/2011/12/faster-canvas-pixel-manipu...


Like any other compiler, function calls sometimes get inlined. And sometimes not. Depending on compiler heuristics of various sorts.


Note that 'in'

    for (key in object)
is for getting keys, in Firefox, meanwhile 'of'

     for (value of iterator)
is for getting values out of an Iterator.


Most of the array methods are explicitly defined in terms of indexing rather that iterators, so for(of) is incorrect. On the other hand indexing is still faster than iteration in the major implementations.


My comment were intended as a direct reply to phpnode's code, 'ignoring' the rest of the thread.

How do you mean when you state that for(of) is incorrect?

Perhaps this 'example' clears something up?

  « for (value in {a:1,b:2,c:3,d:4,e:5}) console.log(value)
  » undefined
    "a"
    "b"
    "c"
    "d"
    "e"
  « for (value of {a:1,b:2,c:3,d:4,e:5}) console.log(value)
  × TypeError: ({a:1, b:2, c:3, d:4, e:5})['@@iterator'] is not a function


the only issue is i'd like to differentiate between iterating arrays and objects at the syntax level. Coffeescript uses `in` for arrays and `of` for objects, but I agree that becomes confusing. Open to other suggestions!


I've been spending some time thinking about CoffeeScript's choice for `in` and `of` and I think I have the answer: they should be more regular. One (probably `of`) should be used for the keys/indexes and the other (probably `in`) should be used for contents.

These are legal CoffeeScript examples:

    for key, value of object
    if key of object

    for value in array
    if value in array

    for index, value of array
    if index of array
The one that's missing is:

    for value in object
    if value in object


The issue with coffeescript is that it uses the opposite syntax to JS - `in` for arrays instead of objects. ES6 introduces the `of` keyword for real iterators so i don't really want to use that for either of them. It's tricky. There are other options but they're verbose

    every element as key, value from arr {
      console.log(key, value);
    }

    every property as key, value from obj {
      console.log(key, value);
    }


Thoughts on this?

    every [key, value] from arr {
      console.log(key, value);
    }

    every {key, value} from obj {
      console.log(key, value);
    }

    every [key] from arr {
      console.log(key);
    }

    every {_, value} from obj {
      console.log(value);
    }
Looks a bit cramped to me but I get the impression that array comprehension is one of the major reasons that people use Coffeescript, so perhaps it's not too much trouble?

There's also the issue with some fonts making it hard to differentiate between { and [ but it's an idea that might be worth to think about at least.


I quite like this suggestion. If we flip the key, value around to make it inline with what forEach etc do, then we don't need the placeholder for iterating without the key:

    fast-each [value] from arr {

    }

    fast-each {value} from obj {

    }
 
    fast-each [value, key] from arr {

    }

    fast-each {value, key} from obj {

    }
The disadvantage is that this looks like array comprehension but isn't.

Alternative:

    fast-properties key, value from obj {

    }

    fast-elements index, value from arr {

    }

    fast-properties value from obj {

    }

    fast-elements value from arr {

    }


That's a though one. I know I can't think of any that aren't either verbose or nondescript.

But if Coffescript can walk away with its choice then I don't think you'll have anything to worry about.


if you've ever written a for loop like this, you'd see the exact same issue.

    for (i = 0, total = arr.length; i < total; i++) {
      item = arr[i];
    }
This will also iterate over gaps in the array. Is this a bug?


This is actually unlikely to be a problem. The edge cases ignored here are actually the same as those ignored by underscore.js, which is obviously a very popular library.


I agree that it's unlikely to be a problem...until your site gets popular and a .01% corner case becomes a weekly occurrence or until someone sees that you're using fast and exploits an attack vector.


it's not that kind of edge case. It simply means that some very uncommon constructs are not supported. If you never use those constructs, which basically nobody does, then it will never fail. (and in fact the failure mode is pretty soft and unlikely to crash your application). If your code worked with this once, it will always work.


lodash is the fast one that pioneered this, underscore for the longest time fell back to slow native ones.


you're right in that it's important to consider inputs of different sizes. I did this for the indexOf() functions, I'll do the same here, thanks!


To prove its worth, try showing a Real use case.


this library does not overwrite any native functions or manipulate any prototypes, you have to call the fast.js versions explictly - it's opt in.


Lo-Dash acts exactly the same way.


An alternative interpretation might be - JavaScript, the high level language language that's so awesome that it can out perform native code*

* as long as you make it do less work


Why isn't the native version doing less work? Isn't that what you expect from a language design, that the native version will be as close to optimal as possible in the first place?


Did you read the article? These functions are not 100% equivalent.


Fair enough. Why doesn't the title of the post say so then? "Faster incomplete versions of Javascript native functions" would have been a better summary.

Or even discuss the fact that if this library is good enough for people to use then maybe the edge cases that the native versions are covering might not be so useful after all?


The native versions have to/should 100% support the language spec and historical behavior. In this instance, it means they can't optimize much that iterates over a sparse array.


As well as the example of "sparse arrays" shown in the README, there are some additional slight gotchas around `.bind()`, e.g. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

These fall outside of the common uses of these methods, and most people don't even know they exist.


author of the library here. The native implementations have to follow the spec exactly, which means that they have to guard against specific edge cases. The reimplementations in fast.js do not follow the spec exactly, they optimise for 99.9% of use cases and totally ignore the 0.1%. This, combined with the fact that the JS is JITed straight into machine code anyway gives fast.js a significant advantage - it does less work and so is faster.


Do you have documentation on the differences in behavior?


I think he meant that he had no affiliation himself


it's a shame for such a distinguished person to make such an amateur mistake - point 10 is indeed answerable:

1. people who put the milk in first have become adept at adding exactly the right amount of milk to a cup of any size. It's a ubiquitous skill, learnt virtually as soon as the person begins drinking tea in this (proper) way. Orwell was clearly inexperienced.

2. adding the milk last requires simultaneous stirring to correctly assess the tea's consistency. This wasteful and complicated activity is not required when the milk is added first, as the milk is evenly mixed with the tea by the pouring process itself. This saves considerable time.

3. adding the milk to an already boiling cup of tea burns the milk, ruining the flavour of the tea.

However, a true tea lover would never soil their tea by adding milk in the first place.


The French upper class were the first to popularise the idea of adding milk to tea. This was back in the days of Napoleon and fine china, as in from China, was new too.

The reason for adding the milk first was to protect their finest quality china from cracking due to the heat of the tea (the teapots were metal, e.g pewter around that time too).

So, the origins of the milk first idea are deeply rooted in history. If you are drinking tea in 18th century fine china tea cups handed down from your aristocratic French ancestors, then you might not want to experiment with the tea first technique, however, if you drink tea out of a mug then consider the benefits of tea first.

As for whether 'tea first' needs a stir, the answer is not yes. There are convection currents inside the cup that will stir the milk in for you. A helping stir does help but is not always necessary particularly if the tea has cooled too much.

> 3. adding the milk to an already boiling cup of tea burns the milk, ruining the flavour of the tea.

No. The tea has to infuse in the teapot before pouring. Therefore it is not boiling by the time it gets to the cup and the milk can't be 'ruined'.

Unless you are using tea bags, teabags are an excellent innovation, personally I prefer single cup tea bags, tea made in cup with none of the paraphernalia of the pot. If you want a sharp cup of tea with no bitter taste an average teabag in cup with boiling water and no milk yet will work perfectly. No need for lengthy infusion time, add milk, get colour right, squeeze and remove bag, sharp cuppa made.

Orwell gets it wrong regarding the matter of drawing fresh water. Most water contains things that lead to limescale. It is important to draw fresh water so that limescale does not build up in the kettle. Dissolved oxygen levels is cited by some as important, theoretically you are boiling the oxygen out of the water too much if you reboil rather than draw fresh. This sort of makes sense and 'experts' say it makes sense but I have not tested this myself or seen a scientific paper explaining how this works.

A final detail: unpasteurised, fresh milk. Tea made with this 'forbidden fruit' is far better than when made with normal milk. The difference is hard to describe, but, to give you an idea it is like the difference between listening to traffic noise on the edge of a motorway and listening to Handel's 'Zadok the Priest' being sung by a choir in Westminster Abbey.


One can become just as adept at stirring the correct number of times. Its a ubiquitous skill too.

Also, this myth about 'burning the milk' - I get my latte at 180 degrees, and the milk is not 'scalded' or 'burned' or any other thing - its just fine.


To make coffee, you need water just below boiling. Commercial brewers are set at about 200 degrees. To make a proper pot of tea, you need boiling water.


I suppose there is a prescribed direction of stirring?


This depends entirely on which hemisphere said tea-maker is located.


North/South or East/West?


The milk in a latte is typically gradually heated to its temperature, whereas when cold milk is added to hot tea, it changes temperature rapidly. This causes the Maillard Reaction, fundamentally changing its flavour. This is like the difference between cooking a steak at immediately high temperature vs gradually increasing temperature. Same resulting temperature but one is delicious and the other is brown and floppy.

0. http://en.wikipedia.org/wiki/Maillard_reaction


Did you actually read the link you provided? The Maillard reaction doesn't appear to be relevent to milk and tea combining at the sub-boiling temperatures discussed. Unless you have another source that actually supports your statement?


Yes, I read it - I was rather hoping no one else would, it seemed just about plausible enough to be convincing.


Refreshing candor.


This is a religious matter and as such no tactics are off limits. Tea first is wrong.


That article has a lot of details without actually describing how the reaction is achieved. You say its by rapid heating instead of gradual heating. So a latte is safe. Have to get the word out to barristas nationwide, since I have to explain to every one that nothing bad is going to happen to my latte.


It seems, at least according to one double blind study[1], that there's not actually a noticeable difference in taste.

[1]: http://tomstafford.staff.shef.ac.uk/teatastetest/


http://en.wikipedia.org/wiki/Lady_tasting_tea

"David Salsburg[5] reports that a colleague of Fisher, H. Fairfield Smith, revealed that in the test, the woman got all eight cups correct.[6] The chance of someone who just guesses getting all correct, assuming she guesses that four had the tea put in first and four the milk, would be only 1 in 70 (the combinations of 8 taken 4 at a time)."


The Sheffield study was inspired by Fisher's early experiment. I don't think a single study performed in 1935 with a single participant provides indisputable proof though, especially given that a later study with 94 participants and more rigorous statistical and experimental methods found no clear difference. It's hard to guess now what factors lead to the lady correctly guessing all 8 cups - perhaps the experiment was poorly designed, perhaps she had exceptional tasting skills, or perhaps it was truly chance (1 in 70 isn't actually exceptionally low odds).


The reason to put in milk afterwards: only then can you marvel at the swirling clouds of milk slowly dissolving in the tea. I don't think extra stirring is necessary. If you are fast enough, there will still be enough motion in the tea from pouring it.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: