It seems to me a swap file is more flexible.
A swap file is more flexible but also more fallible than a swap partition. A filesystem error could damage the swap file. A swap file can be a pain for the administrator, since the file can't be moved or deleted. A swap file can't be used for hibernation. A swap file was slightly slower in the past, though the difference is negligible nowadays.
The advantage of a swap file is not having to decide the size in advance. However, under Linux, you still can't resize a swap file online: you have to unregister it, resize, then reregister (or create a different file and remove the old one). So there isn't that much benefit to a swap file under Linux, compared to a swap partition. It's mainly useful when you temporarily need more virtual memory, rather than as a permanent fixture.
A swap partition can be preferred because it avoids a dependency on the file system when all you need is an addressable memory pool.
But nothing prevents you from using a swap file instead of a swap partition, or in addition to a swap partition.
Create the file:
dd if=/dev/zero of=/extraswap bs=1M count=512
Initialize file contents's:
See if it worked:
In order to start using the swapfile always at bootup, edit /etc/fstab and add
/extraswap swap swap defaults 0 0
Perhaps the main reason is that the main kernel suspend-to-disk does not work with swap files. For example the Debian wiki instructions are to install
uswsusp if you need this.
More recently, swap files do not work if the filesystem is
btrfs, so it is simplest for distributions to always create swap as a partition.
It is vaguely mentioned that using a file for swap had potentially lower performance than a partition, prior to kernel version 2.6. https://www.kernel.org/doc/gorman/html/understand/understand014.html#text15
For completeness I'll add my own answer:
As said by @Gilles, a swap file can't be used for hibernation. When using a swap file, the system must locate the swap file's header, but in order to do this the filesystem that contains the swap file must be mounted, and a journaled filesystem - e.g. ext3, ext4, and basically all modern filesystems used by Linux - cannot be mounted during resume from disk. (In reality, there are ways to do so, but quite cumbersome.)
I think that it is mainly because the access time to the datas located on a partition are lower. The point of the swap file is more to help the sys admin when he is really out of RAM and needs to operate huge operations that would maybe crash his system. In this case he will sporadically create swap files when needed.
But anyway you can have both of them.