Categories
Code Programming WordPress

__DIR__ vs dirname( __FILE__ )

Calling a constant should always be faster than a function call, right? PHP contains two different ways to get the directory that a file is currently in. __DIR__ is a magic constant added to PHP in 5.3. The official PHP documentation specifically states: “This is equivalent to dirname(__FILE__).” Equivalent in return doesn’t necessarily mean equivalent in performance though, so I decided to test the performance of both accross a couple of variables.

Testing Methodology

When running lots of tests, I’ve found that travis-ci can be a big helper. You can define the matrix of the tests you want to run as your testing matrix and then use the results. So I setup a repo for my tests. The repo contains four main pieces:

  1. A file generator which creates the code I’ll actually run the performance test on.
  2. A test running script which runs the actual tests.
  3. The travis.yml file to define my tests matrix
  4. Files used for the actual test. This is not linked, there are 400,000 files. The generator shows them off.

My test calls the function I am looking for 100,000 each. One run has all the files in 1 directory, and the other has one file per directory. I wanted to rule out the possibility that a single directory could affect this call.

I ran this test on six version of PHP: 5.6.40, 7.0.33, 7.1.27, 7.2.15, 7.3.9 and 7.4-dev. Each test did 650 runs and I looked at the user time for each of those runs. This means that I called both __dir__ and dirname( __file__ ) 130,000,000 times each. I then took the times for each of these runs and looked at that maximum (slowest) run for each and the 95% time ( the average between the 618th and 619th slowest) to rule out any extreme cases. Overall, the results between maximum and 95% are similar.

User is the amount of CPU time spent in user-mode code (outside the kernel) within the process. This is only actual CPU time used in executing the process. Other processes and time the process spends blocked do not count towards this figure.

Stack Overflow

__DIR__ vs dirname( __FILE__) Test Results

95% performance

Script5.67.07.17.27.37.4
dir ( 1 folder)1.42.762.082.512.271.3615
dir ( many folders)1.382.292.552.36152.651.57
dirname( 1 folder)1.58152.272.74153.242.411.5215
dirname( many folders)1.682.292.08153.292.68151.87

Overall, the results show that __dir__ is generally faster, but it’s rarely much faster. Consider that in the slowest run ( using PHP 7.2 and calling dirname( __FILE__ ) on multiple folders), each call took 0.0000329 seconds. The fastest run was 2 hundred-thousandths of a second faster. This is such a micro optimization that except under extreme scale, it’s unlikely you will ever notice a difference. That said, under most versions of PHP, __DIR__ is faster.

So: __dir__ or dirname?

At the end of the day, the performance of __DIR__ is ever so slightly better, but more importantly I think it’s clearer and easier to read. So I’m on team __dir__, but the performance is only a bonus.

If you have a different thought, or think that my testing methodology could be improved, please let me know in the comments below.

Categories
Art Code Four Short Things

Four Short Things – 2 March 2019

Inspired by O’reilly’s Four Short Links, here are some of the things I’ve seen, read, or watched recently.

Clicks are an “unreliable seismograph” for a news article’s value — here’s new research to back it up

This is a summary of a report on user behavior on the web. It found a few things that aren’t super surprising:

  • Relevance is the paramount driver of news consumption. People find those stories most relevant that affect their personal lives, as they impinge on members of their family, the place where they work, their leisure activities, and their local community.
  • Relevance is tied to sociability. It often originates in the belief that family and friends might take an interest in the story. This is often coupled with shareability – a wish to share and tag a friend on social media.
  • People frequently click on stories that are amusing, trivial, or weird, with no obvious civic focus. But they maintain a clear sense of what is trivial and what matters. On the whole people want to stay informed about what goes on around them, at the local, national, and international levels.
  • News audiences make their own meanings, in ways that spring naturally from people’s life experience. The same news story can be read by different people as an ‘international’ story, a ‘technology’ story, or a ‘financial’ story; sometimes a trivial or titillating story is appreciated for its civic implications.
  • News is a cross-media phenomenon characterised by high redundancy. Living in a newssaturated culture, people often feel sufficiently informed about major ongoing news stories; just reading the headline can be enough to bring people up to date about the latest events.
  • News avoidance, especially avoidance of political news, often originates in a cynical attitude towards politicians (‘They break rules all the time and get away with it!’), coupled with a modest civic literacy and lack of knowledge about politics.

Jasper Johns: Recent Paintings and Works on Paper

Jasper Johns continues to callback to previous works while introducing new motifs and styles. The 88 year old artist shows off why he is the living artist who’s works sell for the most. This show is on view at Matthew Marks Gallary (522 West 22nd Street) until April 6.

Building a Culture of Safety

Josepha identifies the importance of creating safety when it comes to leadership and identifies what safety is, namely physical, psychological, social, and moral safety. I’ve been really enjoying her writings around leadership lately and has definitely helped me think about how I can apply the ideas to my leadership style.

Spectacle: ReactJS based presentation library

I’ve started researching presentation libraries to see what has changed in the last year. Spectacle was available last I looked, but it seems like it has come a long way and I’m thinking it might be time that I give it a try.

Four Short Things is a series where I post a small collection of links to art, news, articles, videos and other things that are me. Follow my RSS feed to see Four Short Things whenver it comes out.

Categories
Art Code Four Short Things WordPress

Four Short Things – 23 February 2019

Inspired by O’reilly’s Four Short Links, here are some of the things I’ve seen, read, or watched recently.

Leukemia has won

WordPress has allowed me the opportunity to meet hundreds of people first online and then offline, but Alex “Viper007Bond” was the first. When I first started getting involved in WordPress, I spent many late nights in the IRC #wordpress channel on freenode, at first seeking help but then providing it. Viper was commonly there helping others and likely answered more than a few questions of mine as well. He’s been publicly battling leukemia for 2.5 years. His blog is a great tale of the ups and downs of cancer. Alex and those that care about him are in my thoughts right now.

Kevin Beasley: A view of a Landscape

On view at the Whitney until 10 March, this exhibit on the top floor is one encompassing sound and visuals. Featuring the motor from a cotton gin and giant sculptures with Cotton, it explores race, history and the evolution of America.

Writing CSS Algorithms

Lara has done more to change my opinions on CSS than anyone else. This post is a companion piece to a talk she gave at WordCamp US and one that everyone web developer should read.

Pento hits 1000 Commits

13 people have made over 1000 commits to WordPress core over the past nearly 16 years. Gary Pendergast joined the club during the 5.1 release. Overall, there have been 44767 commits so Gary’s count only represents 2.2% of the total activity.

Four Short Things is a series where I post a small collection of links to art, news, articles, videos and other things that are me. Follow my RSS feed to see Four Short Things whenver it comes out.

Categories
Code

Learning Makes Developing Fun

Like many developers, I get into ruts where I'm not excited about what I'm working on. There are pieces of development that each of us doesn't enjoy for some reason. Maybe you hate QA.  Maybe you hate refactoring. Maybe it's writing JavaScript, PHP, CSS, or Go. It doesn't matter what it is for you.  These roadblocks of lack of excitement and interest need to be broken through if you are going to succeed, and one of the best ways to do that is to make things new and fun again through learning. 

Having Fun isn't Hard

When you've got a Library Card 

Arthur

Learning and using new techniques makes things fun again. Coding gets boring when we spend our time doing the same thing over and over again. When we aren't pushing ourselves forward, we are being left behind. It's important to overcome the challenge of doing something new so we continue moving forward.

Here are three things I've read over the last few weeks where I learned something. Maybe one of these will help you learn something new:

  • Linked Lists by Lara Schenck. This is an overview of a data structure that isn't native to any of the languages I spend the majority of my time in. Lara's series on computer science basics is a great primer for those of us without formal CS educations.
  • The Documentation for Styled Components. I was introduced to Styled Components when Laura Medalia started mentioning them on her Instagram Stories. I've started playing around with them to see if they are going to be right for some of the react things I've been doing.
  • A Twitter thread on the Social Model of Disability and Stephen Hawking has helped my thinking about how I speak about disabilities. Hat Tip to Ryelle for sharing it.
Categories
Code

Null Propagation Operator proposal for JavaScript

At it’s January meeting, TC39 (essentially the standards body responsible for JavaScript) heard a proposal for some syntactical sugar that really excites me.  It’s called the Null Propagation operator and allows code that looks like

const firstName = (message
&& message.body
&& message.body.user
&& message.body.user.firstName) || 'default';

to become code that looks like

const firstName = message.body?.user?.firstname || 'default';

Essentially, it allows for eliminating lots of checks to ensure multilevel JavaScript objects are properly defined. This reminds me a bit of the null coalesce operator in PHP as  it allows for easier to read code. It needs to be balanced so these languages don’t turn into Perl filled with secret operators.

The proposal is now in stage 1 which means that TC39 “expects to devote time to examining the problem space, solutions and cross-cutting concerns”. It’s still early to get excited about this, but this is one of those pieces of syntactical sugar that make writing code easier.

Categories
Code

“My Code is Self-Documenting” — Eric Holscher 

Self-documenting code is one of the biggest documentation myths in the software industry. This view generally conflates documentation with code comments. I’d like to make two arguments in this post:

Code comments have value

Documentation has more value than just explaining how software works

Source: “My Code is Self-Documenting” — Eric Holscher – Surfing in Kansas

Categories
Code

New BASH Prompt

For the last few years, I’ve been using impromptu for setting my bash prompt. However, it felt in perpetual beta status and I wanted to try out something new, so today I installed bash-git-prompt and am giving it a try.

It was super easy to get started with it following the instructions.

  • Run brew update
  • Run brew install bash-git-prompt for the last stable release or brew install --HEAD bash-git-prompt for the latest version directly from the repository
  • Now you can source the file in your ~/.bash_profile as follows:
if [ -f "$(brew --prefix)/opt/bash-git-prompt/share/gitprompt.sh" ]; then
  __GIT_PROMPT_DIR=$(brew --prefix)/opt/bash-git-prompt/share
  source "$(brew --prefix)/opt/bash-git-prompt/share/gitprompt.sh"
fi

So far, it seems like something that should do the job. If not, I’ll look for a new solution. Let me know in the comments how you setup and manage your prompt.

Categories
Code Programming

Bash Functions I use for access logs

The command line is my IDE.  Vim is my editor and all the functions and programs in bash help me be a better developer.  As much time as I am writing code though, I also am often spending a lot of time looking through logs to see what is going on.  Over the last five to ten years I’ve collected a number of bash functions to help make working with access log files easier. Some are stolen from my old coworker Drew, others from various places online, and others I’ve cobbled together.

function fawk {
    first="awk '{print "
    last="}'"
    cmd="${first}\$${1}${last}"
    eval $cmd
}

This simple function allows me to pull one whitespace broken element out. Imagine an access file filled with lines like:

172.16.194.2 - - [13/Jan/2017:14:55:31 -0500] "GET /infidelity-husband-had-affair/ HTTP/1.1" 200 20685 "https://www.google.com/" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36" "1.1.1.1, 2.2.2.2, 127.0.0.1, 127.0.0.1"

I can run cat access.log | fawk 7 to pull out the urls. I can further pipe that to sort | uniq -c | sort -nr | head to pull out the most popular urls. I also have a function for visualizing these results.

function histogram {
 UNIT=$1
 if [ -z "$UNIT" ]; then
 UNIT="1";
 fi

 first="sort|uniq -c|awk '{printf(\"\n%s \", \$0); for (i =0; i<\$1; i=i+"
 last=") {printf(\"#\")};}'; echo \"\""
 cmd="${first}${UNIT}${last}"
 eval $cmd
}

For example, If I want to see all the response codes, of the last 500 responses I can do something like

tail -n 500 nginx/access.log | fawk 9 | histogram 10

 466 200 ###############################################
 8 301 #
 5 302 #
 1 304 #
 18 404 ##
 2 429 #

I often want to look at more than one access log at a time, but they are gzipped to save space after rotating. I have a function to cat or zcat all of them.

# cat or zcat all the access logs in a folder 
# Pass in folder to search in as the only param
# Likely want > into another file for further use
access_concat(){
	find $1 -name "acc*" -not -name "*.gz" -exec cat '{}' \;
	find $1 -name "acc*" -name "*.gz" -exec zcat '{}' \;
}

When it comes to working across many servers, I still rely on dancers shell in concert with these functions.  The occasional access log spelunking is much easier with these tools.

Categories
Code

Bash punchcard

When are you using the command line? I use a python script and a change to my HISTTIMEFORMAT to keep track of when I am active on the command line.  Since I use vim, this means that every time I launch my text editor along with every time I run a command is recorded. This is my punch card since I got this computer in July, along with a punchcard of just commands that start with git and just commands that start with vim.

All commands

all git related commands

all vim commands

It’s interesting to see that I open Vim on Mondays much more than I commit code on Mondays. I think I need to spend some time figuring out how to make Mondays a day with more commits.

I first uploaded my bash punch card in 2012. I was much better at only working during the day then. I later did it in 2013 with both my personal and work computers.

Categories
Code

Four rules of thumb for committing code

  • The commit message should explain Why, not what
  • Atomic commit. As small as possible
  • Don’t commit commented out code. Just remove it.
  • Before it goes into master/trunk, always have at least two sets of eyes on it. You only have one set even if you have glasses.