=== vs indexOf()
A Speed Test
The hiring assessment is drawing near, so many of us have started reviewing material during our free time. For me, that's generally on the 40 minute bus ride to-and-from Hack Reactor.
Here's the code I was working on today:
It's a reimplementation of the popular underscore library. The guy sitting next to me was a programmer and took note of this line:
He asked, "Why aren't you using
- A for loop with a conditional if-statement:
- An if-statement using indexOf():
Create A Performance TestJSPerf has a lot of options, almost none of which I will use. It didn't find it necessary.
- Starting on the home page, enter your details so that the site can remember you and your ownership of the tests.
- Enter a title and description.
- A lot of my magic happens in the Preparation code HTML section. Inside a script tag define the functions you want to compare and the variables they need.
- Skip to the Code Snippets to Compare section. Here, I implore you to write useful test titles. My first test is named "Searching array for a value with a for loop". You know exactly what it does. Put your matching function from step three in the Code section. The parameters passed into the function are also the ones you defined before.
Repeat as needed for more tests by clicking Add code snippet.
- Save your test by clicking Save test case.
Warning!EVERY SINGLE TIME I save I get an internal server error.
Ignore it! Your stuff saved. It does not even indicate that you had syntax errors. Back your URL up to its base (given your title) and hit enter:
If You Have Errors
You may have made a mistake in your code at some point. JSPerf will tell you.
Type of the address of your test with
/edit on the end to fix your code.
If you have multiple revisions of your test, you can also type the revision number, then edit.
Run Your Tests
(when everything is working)
- Scroll down, past your beautiful prep code. You can either click on the Run tests button to run them all (recommended) or run them individually by clicking the test names on the left hand column.
- Give it a sec. The tests will show how many Ops/sec (operations per second) can run. It will also make comparisons between the tests. For the more visual among us, scroll down a bit and you will get a graphical representation. If other users have run your code on JFPerf's browse site, there may be other systems represented by the graph, as is the case above.
Here is the test we created:
Turns out using
JSPerf is not perfect or all that easy to use, but it's a good tool for basic speed comparisons. (See what I did there?)comments powered by Disqus