Because Base58 initial
1s carry 8 bits of data, but P2SH addresses cannot be represented with a string with initial
1s so it starts with
3 which, like all other cases & characters, encodes 5.86 bits of data. Since the same number of digits encodes fewer bytes, more digits is needed for P2SH.
The P2PKH network byte is 0x00 and the rest is the hash and the checksum. If the hash also starts with 0 digits, P2PKH address will exploit initial 1's efficiency, while P2SH starts with 0x05 so following digits, even if 1's, are not initial 1's and they will not be subjected to the efficiency shortcut I described above.
The Base58Check algorithms is as below:
The serialized data is "network byte" + "20 byte hash" + "4 byte checksum"
The checksum doesn't change the address length at all. Network byte and the hash do.
The serialized data is encoded in the following way:
- Count initial 0x00s and discard them from the serialized data
For example for mainnet P2PKH addresses (these have network byte = 0x00) if the 20-byte hash starts with 0x
00000a..., then there are 3 initial zeros. For other addresses, such as mainnet P2SH (network byte: 0x05), the hash doesn't need to be considered and the number of initial zeros is zero.
- Base-convert the rest
the standard mathematical operation which can be calculated by long-division. The naive method to calculate this is to represent the binary byte array as a BigNumber and to consider the sequence of remainders.
An octal digit corresponds to 3 binary digits because log_2 (8) = 3. Likewise, a Base58 digit corresponds to log_2 (58) = 5.86 binary digits (a little less than exactly 6 digits, for Base64). This is a result of base-conversion.
Nevertheless, if there are initial 0s, when we consume them, we're subtracting 8 bits from bytes-to-be-read-and-serialized instead of 5.86. This is a result of Satoshi's decision to allow shorter addresses at the cost of a higher variance of address lengths (25-34 characters)
The first byte is the network byte. When it's nonzero (for P2SH, it always is!) then there are no initial zeros and the result is 100% derived from base conversion without the initial-zeros shortcut. Just like a six-digit binary number always has 2 decimal digits, all P2SH mainnet addresses have 34 characters.
NOTE: 7-digit binary numbers can have 2 or 3 digits in decimal. Variability by one digit is also possible in address encoding depending on the network byte. This is not the case with mainnet P2SH, it always has 34 bytes. I know this, because both
6*256^24 - 1 in Base58 have 34 digits. And P2PKH varies by more than one digit because as Pieter Wuille commented, the serialized data of P2SH in binary has a fixed number of digits while that of P2PKH can have many initial zeros (and how those are consumed can be compared to omitting them).