Categorias
PHP Programação

PHP Memory Usage and Performance Improvements Tips

Memory usage and performance improvements make everybody happier, from end-user to cloud and infrastructure engineers. And they are all right, and this is an optimization that we should try to achieve as much as possible.

I am also keeping this page for a reference to my future self because we cannot rely too much on our memory, and that will be a good reference I want to re-visit. I will make constant updates on this page.

Use objects with declared properties over array

Arrays have a larger footprint to avoid constant memory pointers reassignments. It then reserves large amounts of memory when more elements or indexes are added.

Image for array vs object memory usage

Be careful to self-referencing that would prevent garbage collector from work

Garbage collector is working as expected when the internal reference count (how may times a value is used) reaches zero:

$x = "foobar";    // refcount = 1
$y = $x;            // refcount = 2
unset($x);      // refcount = 1
unset($y);      // refcount = 0 -> garbage collector will be happy ==> Destroy!

But self-referencing can be tricky:

$x = [];            // refcount = 1
$x[0] =& $x;    // refcount = 2
unset($x);      // refcount = 1
                    // It will never come to zero due to cycle

The cycle collector will eventually destroy it, but it will hang on memory for a while anyway.

Sprintf vs double/single quote concatenation

A very common use case is string concatenation or interpolation when you want to add a variable into a static string. It is interesting to note that:

If you have PHP < 7.4, use double-quote interpolation or single quote concatenation over sprintf function.

<?php 

$this->start($loop);

ob_start();

for ($i = 0; $i < $this->loop; ++$i) {
    print 'Lorem '.$i.' ipsum dolor sit amet, consectetur adipiscing elit. Proin malesuada, nisl sit amet congue blandit';
}

ob_end_clean();

return $this->end();

If you have PHP greater than 7.4, use sprintf:

<?php 

$this->start($loop);

for ($i = 0; $i < $this->loop; ++$i) {
    $value = sprintf('Lorem %s ipsum dolor sit amet, consectetur adipiscing elit. Proin malesuada, nisl sit amet congue blandit', $i);
}

return $this->end();

PHP Benchmarking

PHPBench.com was constructed as a way to open people's eyes to the fact that not every PHP code snippet will run at the same speed. You may be surprised at the results that this page generates, but that is ok. This page was also created so that you would be able to find discovery in these statistics and then maybe re-run these tests in your own server environment to play around with this idea yourself, by using the code examples (these code examples are automatically generated and as the code in my .php files change, so do they).

PHP benchmarks and optimizations

Collection of tests and benchmarks for common operations in PHP. Tests run on several versions of PHP. There is an option to compare different solutions for the same problem to compare performances between them, such as checking values with isset against !empty.

Categorias
Tropeçando

Tropeçando 101

Minimal safe Bash script template

Bash scripts. Almost anyone needs to write one sooner or later. Almost no one says “yeah, I love writing them”. And that’s why almost everyone is putting low attention while writing them.

I won’t try to make you a Bash expert (since I’m not a one either), but I will show you a minimal template that will make your scripts safer. You don’t need to thank me, your future self will thank you.

Software Architecture Books

A comprehensive list of books on Software Architecture.

People in the software industry have long argued about a definition of architecture. Ralph Johnson famously defined software architecture as "the important stuff (whatever that is)." I, subjectively, followed his definition while deciding whether or not to include a specific book.

8 Tips to Master Asynchronous Communication

Great tips for using asynchronous communication in your favour. It’s the reason why some remote teams thrive while others grapple with anxiety and exhaustion.

POSTGRESQL: LIMIT VS FETCH FIRST ROWS … WITH TIES

Most people in the SQL and in the PostgreSQL community have used the LIMIT clause provided by many database engines. However, what many do not know is that LIMIT / OFFSET are off standard and are thus not portable. The proper way to handle LIMIT is basically to use SELECT … FETCH FIRST ROWS. However, there is more than meets the eye.

PostgreSQL Parallelism Do’s and Don’ts

PostgreSQL can apply parallel processing to speed up query performance. But the PostgreSQL query planner and internals are complex, making it a challenge to predict how parallel processing will affect different queries.

In this webinar, you’ll learn parallelism best practices to maximize your PostgreSQL query performance.

Categorias
Tropeçando

Tropeçando 100

How Exception to the Convention Does More Harm than Good

We have a project, and to make it easier, we use specific standards. E.g., we use spaces in every file.

But sometimes, we get to a situation when these standards are stressful. We don't understand them and just want them to bend over. How does our short-term need for pleasure affects long-term well-being of the project?

Splitting a Domain Across Multiple Bounded Contexts

How designing for business opportunities and the rate of change may give you better contexts.

Your Jest Tests are Leaking Memory

Jest is designed in a way that makes memory leaks likely if you’re not actively trying to squash them. For many test suites this isn’t a problem because even if tests leak memory, the tests don’t use enough memory to actually cause a crash. That is, until you add one more test and suddenly the suite comes apart. In this article, we’ll walk through why it’s so easy for Jest to leak memory, how to tell if your tests have a memory leak, and then how to debug and eliminate leaks in your tests. Even if you don’t use Jest, it’s still useful to understand the process in case you need to debug memory leaks in other javascript code.

How to handle flaky tests

Flaky tests are automated tests that are non-deterministic. That means they may pass or fail when executed against the same build artifact or deployed system.

If you’ve ever retried the execution of a failed test run in your CI/CD pipeline tool without any code or config changes in order to get a failing test case to pass, that’s an indicator that you have a flaky test case.

Why Serverless Teams Should Embrace Continuous Refactoring

Serverless adoption brings promises to many organizations! Promises of cost efficiency, engineering efficiency, and business efficiency. However, serverless is not a technology that, once successfully adopted, can be left unattended to rust.

The motivation to adopt serverless should never be to get the job done and never look back. If you adopt it with this attitude you will inevitably get into the legacy migration juggernaut that will haunt you much sooner than you anticipated.

Categorias
Tropeçando

Tropeçando 99

Diataxis

A SYSTEMATIC FRAMEWORK FOR TECHNICAL DOCUMENTATION AUTHORING.

The Diátaxis framework aims to solve the problem of structure in technical documentation. It adopts a systematic approach to understanding the needs of documentation users in their cycle of interaction with a product.

Conventional Commits

The Conventional Commits specification is a lightweight convention on top of commit messages. It provides an easy set of rules for creating an explicit commit history; which makes it easier to write automated tools on top of. This convention dovetails with SemVer, by describing the features, fixes, and breaking changes made in commit messages.

Awesome list

Awesome list of awesome technology related things

Postgres Observability

Graphical cheat-sheet for PostgreSQL Observability views and functions. You have a visual representation of the services touched by each observability tool, such as buffer, write-ahead logs, query plan, table storage, index information, etc.

An Introduction to PostgreSQL Performance Tuning and Optimization

This document provides an introduction to tuning PostgreSQL and EDB Postgres Advanced Server (EPAS), versions 10 through 13. The system used is the RHEL family of linux distributions, version 8. These are only general guidelines and actual tuning details will vary by workload, but they should provide a good starting point for the majority of deployments.

Categorias
Tropeçando

Tropeçando 98

Operating Lambda: Debugging code – Part 1
Operating Lambda: Debugging configurations – Part 2
Operating Lambda: Debugging configurations – Part 3

In the Operating Lambda series, I cover important topics for developers, architects, and systems administrators who are managing AWS Lambda-based applications. This three-part series discusses core debugging concepts for Lambda-based applications.

Those pesky pull request reviews

They’re everywhere. In Slack: “hey, can I get a review on this?” In email: “Your review is requested!” In JIRA: “8 user stories In-Progress” (but code-complete). In your repository: 5 open pull requests. They’re slowing your delivery. They’re interrupting your developers.

How can we get people to review pull requests faster??

Operating Lambda: Using CloudWatch Logs Insights

In the Operating Lambda series, I cover important topics for developers, architects, and systems administrators who are managing AWS Lambda-based applications. This three-part series discusses monitoring and observability for Lambda-based applications and covers:

  • Using Amazon CloudWatch, CloudWatch Logs Insights, and AWS X-Ray to apply monitoring
    across services.
  • How existing monitoring concepts apply to Lambda-based applications.
  • Troubleshooting application issues in an example walkthrough.
    This post explains how to use CloudWatch Logs Insights in your serverless applications.

CDK Lambda Deployment takes about a minute - how about sub second Function Code Deployment?

Creation of Lambda infrastructure with the CDK is really powerful. Updating the Function code is really slow. Here is a fix for that to get to a sub-second Lambda function deployment time.

Best practices for developing cloud applications with AWS CDK

In this post, we discuss strategies for organizing the development of complex cloud applications with large teams, using the AWS Cloud Development Kit (AWS CDK) as a central technology. AWS CDK allows developers and administrators to define their cloud applications using a familiar programming language, such as TypeScript, Python, Java, or C#. Applications are organized into stages, stacks, and constructs, which allows for modular design techniques in both runtime logic (such as AWS Lambda code or containerized services) and infrastructure components such as Amazon Simple Storage Service (Amazon S3) buckets, Amazon Relational Database Service (Amazon RDS) databases, and network infrastructure.

Categorias
Tropeçando

Tropeçando 97

The Missing Guide to AWS API Gateway Access Logs

In this post, we’re continuing the deep dive on API Gateway. Here, we’ll be looking at API Gateway access logging. Access logging can save your bacon when debugging a gnarly API Gateway issue, but you need to understand some nuance before you can use it correctly. We’ll dig into the details here so that you’ll be logging like Paul Bunyan in no time.

Ready for changes with Hexagonal Architecture

Netflix considerations related to the decisions of using Hexagonal Architecture

OAuth Patterns and Anti-Patterns RefCard

Modern, more secure recommendations continue to replace some of OAuth's original elements as the protocol evolves. Securing access to APIs and other resources and data effectively under OAuth 2.0 requires first learning the components and tools it involves.

Can auto_explain (with timing) have low overhead?

Some benchmarks for use of auto_explain. It seems great to be enabled on production.

Here we’ll be looking into the overhead of auto_explain. Many places warn about its overhead, but I’ve found concrete information difficult to come by.

Setting up SSL authentication for PostgreSQL

PostgreSQL is a secure database and we want to keep it that way. It makes sense, then, to consider SSL to encrypt the connection between client and server. This posting will help you to set up SSL authentication for PostgreSQL properly, and hopefully also to understand some background information to make your database more secure.

Categorias
Tropeçando

Tropeçando 96

Refinement Code Review

With the right environment, I can look a bit of code written six months ago, see some problems with how it's written, and quickly fix them. This may be because this code was flawed when it was written, or that changes in the code base since led to the code no longer being quite right. Whichever the cause, the important thing is to fix problems as soon as they start getting in our way. As soon as I have an understanding about the code that wasn't immediately apparent from reading it, I have the responsibility to (as Ward Cunningham so wonderfully said) take that understanding out of my head and put it into the code. That way the next reader won't have to work so hard.

After all, many problems that code reviews seek to remedy are problems that only become problems when the code is read in the future.

MONITORING REPLICATION: PG_STAT_REPLICATION

PostgreSQL replication (synchronous and asynchronous replication) is one of the most widespread features in the database community. Nowadays, people are building high-availability clusters or use replication to create read-only replicas to spread out the workload. What is important to note here is that if you are using replication, you must make sure that your clusters are properly monitored.

The purpose of this post is to explain some of the fundamentals, to make sure that your PostgreSQL clusters stay healthy.

POSTGRESQL: WHAT IS A CHECKPOINT?

Check some information about checkpoints, mix and max wal size, how they operate toghether and what they play on our day-to-day database workload.

Checkpoints are a core concept in PostgreSQL. However, many people don’t know what they actually are, nor do they understand how to tune checkpoints to reach maximum efficiency. This post will explain both checkpoints and checkpoint tuning, and will hopefully shed some light on these vital database internals.

Boos your user defined functions in PostgreSQL

Using the RDBMS only to store data is restricting the full potential of the database systems, which were designed for server-side processing and provide other options besides being a data container. Some of these options are stored procedures and functions that allow the user to write server-side code, using the principle of bringing computation to data, avoiding large datasets round trips and taking advantage of server resources. PostgreSQL allows programming inside the database since the beginning, with User Defined Functions (UDFs). These functions can be written in several languages like SQL, PL/pgsql, PL/Python, PL/Perl, and others. But the most common are the first two mentioned: SQL and PL/pgsql. However, there may be “anti-patterns” in your code within functions and they can affect performance. This blog will show the reader some simple tips, examples and explanations about increasing performance in server-side processing with User Defined Functions in PostgreSQL. It is also important to clarify that the intention of this post isn’t to discuss whether Business Logic should be placed, but only how you can take advantage of the resources of the database server.

The career-changing art of reading the docs

Don’t wait for knowledge to find you through years of inefficient trial and error. Go get it. And the most convenient, comprehensive place to grab it was there in front of you all along.

Read the docs.

Categorias
Tropeçando

Tropeçando 95

Windy - TailwindCSS

Transform every element on any website into Tailwind CSS

AWS Workshops

This website lists workshops created by the teams at Amazon Web Services (AWS). Workshops are hands-on events designed to teach or introduce practical skills, techniques, or concepts which you can use to solve business problems.

Well-Architected AWS

The Well-Architected framework has been developed to help cloud architects build the most secure, high-performing, resilient, and efficient infrastructure possible for their applications. This framework provides a consistent approach for customers and partners to evaluate architectures, and provides guidance to help implement designs that will scale with your application needs over time.

This repository contains documentation and code in the format of hands-on labs to help you learn, measure, and build using architectural best practices. The labs are categorized into levels, where 100 is introductory, 200/300 is intermediate and 400 is advanced.

Fallacies of distributed computing

false assumptions that programmers new to distributed applications invariably make.

Understanding DynamoDB Condition Expressions

Some use cases to understand this powerful yet misunderstood feature of DynamoDB. There are also examples of bad use of it.
Categorias
Tropeçando

Tropeçando 94

https://extendsclass.com/

ExtendsClass provides tools directly usable in a browser. It saves you from having to install add-ons to your browser in order to add features.

You have at your disposal syntax validators, code formatters, testers, HTTP clients, mock server, but also a SQLite browser.

These are small and easy-to-use tools that can help when you do not want to install software on your workstation.

Solid Relevance

More topics that highlighs the importance of SOLID concepts. How they are key to develop a solid application.

Kubernetes: ClusterIP vs NodePort vs LoadBalancer, Services, and Ingress — an overview with examples

Dockerfile best practices

Writing production-worthy Dockerfiles is, unfortunately, not as simple as you would imagine. Most Docker images in the wild fail here, and even professionals often[1] get[2] this[2] wrong[3].

This repository has best-practices for writing Dockerfiles that I (@slimsag) have quite painfully learned over the years both from my personal projects and from my work @sourcegraph. This is all guidance, not a mandate - there may sometimes be reasons to not do what is described here, but if you don't know then this is probably what you should be doing.

How to Make Your Code Reviewer Fall in Love with You

When people talk about code reviews, they focus on the reviewer. But the developer who writes the code is just as important to the review as the person who reads it. There’s scarcely any guidance on preparing your code for review, so authors often screw up this process out of sheer ignorance.

This article describes best practices for participating in a code review when you’re the author. In fact, by the end of this post, you’re going to be so good at sending out your code for review that your reviewer will literally fall in love with you.

Categorias
Tropeçando

Tropeçando 93

CQRS Is an Anti-Pattern for DDD

Are you interested in new ways to build better software systems? If you work with distributed systems or build any kind of web application, you most likely have heard of the new trends like using Domain-Driven Design with Event-Sourcing and Command Query Responsibility Segregation (CQRS). Well, they are not exactly brand new. However, they are now becoming increasingly popular.

nip.io/

Dead simple wildcard DNS for any IP Address

Stop editing your /etc/hosts file with custom hostname and IP address mappings.

The Tighten Test: 12 Steps to a Better Team

Twenty years ago today, Joel Spolsky (who later co-founded Stack Overflow) published The Joel Test: 12 Steps to Better Code listing 12 metrics for rating the quality of a software development team. The premise is simple: you get 1 point for each “yes” answer, for a total score of up to 12 points.

Architecture decision records, also known as ADRs, are a great way to document how and why a decision was reached within a codebase. We’ve started to adopt them within the mobile team here at GitHub, documenting decisions that affect the iOS codebase and Android codebase, as well as decisions that affect both mobile clients.

ADRs are not the most common within open source codebases, but have gained more popularity since ~2017 within long-lived, “evolutionary” codebases like those in more enterprise-y settings.

So why write an ADR? Why spend time documenting something when a decision has already been made?

https://free-for.dev/

This is a list of software (SaaS, PaaS, IaaS, etc.) and other offerings that have free tiers for developers.